#!/bin/bash
#(c) Copyright Barry Kauler Oct. 2011, http://bkhome.org
#License: Oct. 2011, GPL3 (refer /usr/share/doc/legal)
#A GUI when start desktop first time, to replace the text-mode dialogs (locale, keyboard-layout, timezone)
#inspired by shinobar's countrywizard.qs (firstrun), but a complete rewrite.
#replaces the old single-purpose scripts: chooselocale timezone-set (now symlinks)
#propose first startup, run 'quickcountry, which is symlink.
#111019 first version.
#111020 'countrywizard', 'xrandrshell' now symlinks to 'quicksetup'.
#111022 even though LANG=en_US.UTF-8, localedef still creates /usr/lib/locale/en_US.utf8. use UTF8=.utf8
#111025 thanks to thunor, fix for window dimensions.
#111026 added button for dead mouse.
#111027 fix Xorg.0.log records 'intel' driver loading twice.
#111027 tweaked text messages very slightly.
#111027 first boot, /etc/localtime does not exist, so must set timezone.
#111103 other entries in Etc dir.
#111107 changed 'comboboxtext' to 'combobox' tag, but does not support 'default' tag.
#111111 revert to 'comboboxtext' due to heavy cpu usage, but not 'default' -- do not get the double-popup problem.
#111113 upgraded gtk to 2.24.8, fixed slowness. go back to 'combobox'.
#111113 fix timezone-set cli app.
#120209 scripts fixdesk and fixmenus translate files to new language (as specified in /usr/share/sss/menu_strings and desk_strings).
#120213 when locale change, inform if langpack PET needed.
#120215 offer to translate initrd.
#120215 rc.country calls 'chooselocale cli quiet', to run localedef without asking any questions or popups.
#120216 insert /PUPPYKEYMAP into initrd. moved SET_KEYBOARD before SET_LOCALE processing.
#120216 call 'lang2initrd'
#120224 load console font. (code based on that in 'init')
#120226 redraw desktop drive icons when resolution changes (or may change, in the case of running xorgwizard).
#120227 set hostname, but only if ethernet auto-connected at 1st boot.
#120228 L18L: enabling adding locale without utf8 using regexp.
#120301 no, don't load console font here. seems to get dropped on exit from X. (instead, do it in xwin. now have /sbin/load_consolefont)
#120305 check if langpack available in noarch repo.
#120311 change persistence logic for 120227.
#120313 hardcode translations for popup if user changes locale.
#120313 restrict network frame to only be in main quicksetup window.
#120315 dutch (nl) hardcode translation for locale-change popup. added pt, es, it.
#120328 have rewritten rc.country, try to make chooselocale compatible. 120330 bugfix.
#120331 added Polish (pl) hardcoded translation.
#120401 change logic to call lang2initrd.
#120402 expand locale help window.
#120524 Please wait... msg after click ok button.
#120625 always display network frame, remove set-hostname button, added firewall and ntp checkboxes.
#120627 support kbd pkg.
#120708 'quickarm' symlink to 'quicksetup', for booting on arm boards. see also /etc/rc.d/BOOTCONSTRAINED and /usr/sbin/delayedrun.
#120714 revert 120708. instead, read BOOT_BOARD to determine type of board booting off. support raspberry pi audio settings.
#120717 remove XPID=""
#120901 /usr/share/zoneinfo layout has changed (ubuntu precise).
#130131 xrandr may have more than one frequency on a line, ex:   1360x768       59.8     60.0
#130202 130131 not enough. xrandr was not setting chosen vertical frequency.
#130203 fix insertion of fontsize in xml.
#130506 detect current xorg driver broken, use same code as in /usr/sbin/report-video.
#130511 hostname-set now may return value 2.
#130701 network frame now always displayed. added checkbox for run apps as spot.
#131121 fix the xrandr resolution and refresh rates, displays all now, 01micko.
#131121 fix numerous calls to sed and replace many cut calls with bash, KRG
#131230 zigbert: gui (gtkdialog) improvements.
#170609 crda wireless country selection, ref: http://barryk.org/news/?viewDetailed=00409.

[ "`whoami`" != "root" ] && exec sudo -A ${0} ${@}

export TEXTDOMAIN=quicksetup
export OUTPUT_CHARSET=UTF-8
. gettext.sh

. /etc/DISTRO_SPECS
. /etc/rc.d/PUPSTATE
. /etc/rc.d/BOOTCONFIG
. /etc/clock
. /etc/rc.d/BOOTCONSTRAINED #120714

PARAM1=""
[ $1 ] && PARAM1="$1"
PARAM2=""
[ $2 ] && PARAM2="$2"
TABCHAR="`echo -n -e '\t'`"

[ "$PARAM1" = "composeonly" ] && unset DISPLAY
[ "$PARAM1" = "cli" ] && unset DISPLAY

MYBASE=$(basename $0)
WINICON="gtk-preferences"; HELPICON="gtk-index" #gtk-info
SET_LOCALE=""; SET_TIMEZONE=""; SET_KEYBOARD=""; SET_X=""; SET_COUNTRY=""; SET_XRES=""; SET_XWIZARD=""; SET_NETWORK=""
WINTITLE=$(gettext "Quick Setup")
COUNTRYFRAMETITLE=$(gettext 'Country')
XFRAMETITLE=$(gettext 'Graphics')
BACKTITLE=$(gettext '<b>Quick setup</b>. All these settings (and many more) are available from the Setup and Desktop menu. Please set these to suit yourself, then click <b>Ok</b>')
ICON="puppy_config"
NOSPLASH=1
#specific-purpose utilities...
case $MYBASE in
 chooselocale)
  WINTITLE=$(gettext "Choose Locale")
  BACKTITLE=$(gettext 'Set font, money and language for your location')
  ICON="country"
  COUNTRYFRAMETITLE=$(gettext 'Language and Country')
  SET_LOCALE="yes"
  ;;
 timezone-set)
  WINTITLE=$(gettext "Choose Timezone")
  BACKTITLE=$(gettext 'Set time and date for your location')
  ICON="country"
  COUNTRYFRAMETITLE=$(gettext 'Timezone')
  SET_TIMEZONE="yes"
  ;;
 chooselayout)
  WINTITLE=$(gettext "Choose keyboard layout")
  BACKTITLE=$(gettext 'Choose keyboard layout for your country, or whatever keyboard you are using')
  ICON="country"
  COUNTRYFRAMETITLE=$(gettext 'Keyboard Layout')
  SET_KEYBOARD="yes"
  ;;
 countrywizard|quickcountry)
  WINTITLE=$(gettext "Country Setup")
  BACKTITLE=$(gettext 'Country settings is required for correct keyboard layout, time zone, language, currency, decimal separator, calendar... Please set these to suit your country and language')
  ICON="country"
  COUNTRYFRAMETITLE=$(gettext 'Country Settings')
  SET_LOCALE="yes"
  SET_TIMEZONE="yes"
  SET_KEYBOARD="yes"
  ;;
 xrandrshell)
  WINTITLE=$(gettext "Change Resolution")
  BACKTITLE=$(gettext 'These are available resolutions that the <b>xrandr</b> utility can change the screen to. Please choose the one that you would like to test.')
  ICON="graphics"
  SET_XRES="yes"
  XFRAMETITLE=$(gettext 'Screen Resolution')
  ;;
 *) #quicksetup
  NOSPLASH=0
  case $BOOT_BOARD in
   raspi) SET_LOCALE="yes"; SET_TIMEZONE="yes"; SET_KEYBOARD="yes"; SET_NETWORK="yes"; SET_RP_AUDIO="yes"; SET_RP_VIDEO="yes" ;; #120714 Raspberry Pi
   *) SET_LOCALE="yes"; SET_TIMEZONE="yes"; SET_KEYBOARD="yes"; SET_XRES="yes"; SET_XWIZARD="yes"; SET_NETWORK="yes" ;; #normal quicksetup.
  esac
 ;;
esac
[ "$SET_LOCALE" -o "$SET_TIMEZONE" -o "$SET_KEYBOARD" ] && SET_COUNTRY="yes"
[ "$SET_XRES" -o "$SET_XWIZARD" ] && SET_X="yes"

XPID=0
if [ $DISPLAY ];then
 if [ "$PARAM1" != "nosplash" -a $NOSPLASH -eq 0 ];then
  WELCOMEMSG=$(printf "$(gettext 'Welcome to %s!')" "$DISTRO_NAME $DISTRO_VERSION")
  /usr/lib/gtkdialog/box_splash -placement center -close never -fontsize large -icon_width 60 -icon /usr/share/pixmaps/puppy/puppy.svg -text "$WELCOMEMSG" &
  XPID=$!
 fi
fi

#help dialogs
help (){
 case "$1" in
  keyboard)
   HEADING="`gettext 'Keyboard Layout'`"
   echo "$(gettext 'Computer keyboards have different layouts, depending on the country and language.

<b>Note:</b> After making a choice here, clicking the <b>OK</b> button will update the layout in X (graphical desktop) but not the console (when X not running) -- that requires a reboot.

<b>Technical</b>
The choice made here is saved in /etc/keymap. The value specifies a console layout, from the directory /lib/keymaps. When X starts, the startup script /usr/bin/xwin translates that to the equivalent for X, from directory /etc/X11/xkb/symbols -- note, if no match is found, X falls back to using <b>us</b> layout -- please report if that happens to you.')" > /tmp/box_help
   ;;
  numlock)
   HEADING="`gettext 'Keyboard Numlock'`"
   echo "$(gettext 'Most keyboards have a group of keys on the right side of the keyboard that are labeled <b>0</b> to <b>9</b>. These are intended for when heavy entry of numbers is required. They are dual-purpose, that is can also serve as arrow-keys, Home, End, PgUp, PgDn -- and the latter is usually the default. That is, numlock defaults to off.

If the checkbox is ticked, numlock will be on when X starts.

<b>Technical</b>
The file ~/Startup/numlockx specifies whether numlock is on or off. if the file attribute is executable, then it will execute when X starts. The file contains either <b>numlockx on</b> or <b>numlockx off</b>, and may be edited directly if desired.')" > /tmp/box_help
   ;;
  timezone)
   HEADING="`gettext 'Time Zone'`"
   echo "`gettext 'This needs to be set to ensure that Puppy knows the correct time and date.
If you cannot find an entry for your location, choose one of the <b>GMT</b> entries. Finding the correct entry is best, as it automatically applies DST (Daylight Saving Time), whereas the GMT entries are fixed offsets from the GMT (UTC) reference.

<b>Technical</b>
After making a choice, /etc/localtime will point to the appropriate timezone file in /usr/share/zoneinfo.'`" > /tmp/box_help
   ;;
  utc) 
   HEADING="`gettext 'UTC'`"
   echo "`gettext 'All computers have a hardware clock that runs continuously from a battery, even when the computer is turned off. This clock can be set either to the local time or to UTC.

<b>UTC/GMT</b>
UTC is Coordinated Universal Time, which is basically the same as GMT, Greenwich Mean Time. The latter is the time at the Royal Observatory in Greenwich, London -- this is a time that does not have daylight saving or summer time as does the rest of the UK. It is said to simplify things if the computer hardware clock is set to UTC.

<b>Local time</b>
By default, Puppy Linux assumes that the hardware clock is set to local time, as this is what MS DOS and Windows systems normally use. If you were to change the hardware clock to UTC, you would also have to ensure that all operating systems recognise that, else they will show the wrong time/date.'`" > /tmp/box_help
   ;;
  locale)
   HEADING="`gettext 'Locale'`"
   echo "$(gettext "The locale setting provides money, date and font localization for your country.

The format is, for example, <b>en_US</b> where <b>en</b> designates the language and <b>US</b> designates the country in which it is spoken and written.

When you choose a non-English locale, you will also need a langpack PET package to provide full translation for applications in Puppy. You will receive more information about this after choosing the locale. Currently, we have these langpacks, with the (Forum) names of the maintainers shown:
<i>Danish (da):  maans
Dutch (nl):   Bert
French (fr):  esmourguit
German (de):  L18L
Greek (el):   kounelii
Italian (it): vicmz (temporary)
Polish (pl):  robwoj44
Portuguese (pt): vicmz
Russian (ru): rodin.s
Spanish (es): vicmz</i>")

$(gettext 'Currently installed langpack:') <b>${INSTLANGPACK}</b>

$(gettext "Note: Even if no langpack is available for your language and country, choosing the correct locale does provide some useful localization. However, all the applications, menus and documentation will be in English.")

$(gettext "<b>Technical</b>
The chosen locale file is generated in /usr/lib/locale (if not already) and LANG variable set in /etc/profile.")" > /tmp/box_help
   ;;
  utf8)
   HEADING="`gettext 'UTF-8'`"
   echo "`gettext 'UTF-8 is a Unicode standard in which international characters are represented in 8, 16 or more bits, and plain ASCII (8th bit = 0) text files are valid UTF-8 encoding. UTF-8 has become the defacto standard in Linux. The reason is, basically, that UTF-8 encoded files can be used anywhere in the world and do not need a particular <b>character set</b> translation.

<b>Note 1:</b> Many Puppy Linux users do not use UTF-8 as there is a slight speed penalty running applications -- all English users are ok running without UTF-8.

<b>Note 2:</b> Non-unicode rendering is achieved by 8-bit character sets, such as ISO-8859-1 for normal Latin1 English, or ISO-8859-2 for Eastern European Latin2 languages.

Basically, if your language is not a <b>Latin</b> derivative, such as all Asian languages, then you will need UTF-8. Most non-English Linux users enable UTF-8, even for Latin-derivative languages, <b>so recommend tick the box</b>!'`" > /tmp/box_help
   ;;
  ntp)
   HEADING="`gettext 'NTP'`"
   echo "$(gettext "This will synchronise the local time and date to an NTP server on the Internet. You do not need to do this, as computers normally have their date and time set by a battery-backed hardware clock. However, some tiny computers, such as some ARM boards (for example the Raspberry Pi) do not have a hardware clock, so you either have to set the time/date manually at every bootup, or enable NTP. Note, if you enable NTP now, you can change the settings any time in the future -- see the 'Psync' entry in the 'Desktop' menu.")" > /tmp/box_help
   ;;
  firewall)
   HEADING="`gettext 'Firewall'`"
   echo "$(gettext "It is always recommended that the firewall be enabled when connected to a network, unless it is a local trusted network. Note that you can run the Firewall Wizard any time in the future if you want to change the settings -- see the 'Setup' menu.")" > /tmp/box_help
   ;;
  net)
   HEADING="`gettext 'Network'`"
   echo "$(gettext "Your computer has been assigned a unique name, known as the 'hostname', by which it identifies itself on a network.") $(eval_gettext "It is currently named '\${HOSTNAME}', however you might wish to change that to a name that is more meaningful to yourself, such as 'johnsmithpc'.") $(gettext "The hostname can have letters and numbers, no spaces.")" > /tmp/box_help
   ;;
  resolution)
   HEADING="`gettext 'Screen Resolution'`"
   echo "`gettext '<b>Screen resolution</b>
The choices are in the format, for example, <b>1024x768</b>, which means 1024 pixels (dots) horizontally and 768 pixels vertically.

<b>Refresh frequency</b>
Also listed is the vertical refresh frequency, for example <b>1024x768 60.0</b> means that the screen is refreshing (redrawing) 60 times per second. For older cathode-ray-tube monitors, a value of at least 75 is required to minimize flicker. For modern LCD screens, 60 is satisfactory, and even preferred in most cases.

<b>Warning 1</b>
After testing a resolution, you will be given the opportunity to make it permanent if you wish. <b>IF THE NEW RESOLUTION MESSES UP THE SCREEN, WAIT 60 SECONDS OR PRESS CTRL-ALT-BACKSPACE</b>

<b>Warning 2</b>
This resolution selection box uses the <b>xrandr</b> utility to set the resolution, and is intended for testing only, not for a permanent change, as this does not really change the default resolution, instead it switches resolutions after X has started, which causes a delay and flicker at startup and may have other undesirable side-effects. With some X drivers/hardware it may not work at all. Instead, run the Video Wizard to choose a permanent resolution.'`" > /tmp/box_help
   ;;
  crdw) #170609...
   HEADING="`gettext 'CRD wireless'`"
   echo "`gettext '<b>CRD wireless</b>
A wireless network in a home or office will broadcast on a channel. These are radio frequencies and are numbered 1 to 14. Some countries support only a subset of these channels, and it is possible that a network could use a channel that the Linux kernel thinks is invalid for the country, hence will ignore it.
    
If a channel is ignored, using a network manager, such as <b>SNS</b> (Simple Network Setup), will not find that network.
    
<span color="red">Recommend, leave the setting at <b>00</b> (unset), unless you encounter the problem of being unable to see a wireless network. Setting it may cause a longer time to establish the wifi connection.</span>
    
<b>Technical notes</b>
A list of country codes is in /etc/iso3166-1-alpha2, and /etc/modprobe.d/crdw.conf has the currently selected country code. QuickSetup may be used to change the setting, and this will create /etc/modprobe.d/crdw.conf which sets country code when the cfg80211 kernel module loads, which also informs the kernel (verifiable by "iw reg get").'`" > /tmp/box_help
   ;; #170609 end
 esac
 /usr/lib/gtkdialog/box_help "$HEADING" dialog-info.svg &
}
export -f help

###Network###
#120227 hostname set but only if network connection already available on 1st boot...
#120311 change the logic, allow this frame to persist...
NETWORK_XML=""
if [ "$SET_NETWORK" ];then
 SET_NETWORK=""
 if [ ! -f /var/local/quicksetup-network-check-flag1 ];then
   touch /var/local/quicksetup-network-check-flag2
    IFCONFIG="`ifconfig | grep '^[pwe]' | grep -v 'wmaster'`" #test network interface up only.
    if [ "$IFCONFIG" ];then
     touch /var/local/quicksetup-network-check-flag1
    fi
 fi
fi

if [ "$MYBASE" = "quicksetup" ];then #120313 only allow in main quicksetup window.

   # check connectivity for state of firewall checkbox
   if wget -q --spider -T 4 http://distro.ibiblio.org ;then # returns other than 0 we're not connected
     ONLINE='true'
     FWTT=$(gettext "Tick checkbox to activate the firewall (recommended)")
   else
     ONLINE='false'
     FWTT=$(gettext "Firewall can not be activated until you are connected")
   fi

    #130701 removed this condition, always display network frame...
    SET_NETWORK="yes"
    HOSTNAME="`cat /etc/hostname`" #do not use $HOSTNAME, as hostname-set may have just been run.

    #120625 firewall checkbox...
    DEFAULT_FIREWALL='false'
    #[ "`lsmod | grep '^iptable'`" != "" ] && DEFAULT_FIREWALL='true' # a bad test
    [ `iptables -L -n |wc -l` -gt 10 ] && DEFAULT_FIREWALL='true' # not much better!

    #120625 get time/date off internet...
    CHKBOXNTP=""
    if [ "`cat /root/.packages/woof-installed-packages /root/.packages/user-installed-packages | grep '^[Pp]sync'`" != "" ];then
     DEFAULT_NTP='false'
     #[ -x $HOME/Startup/timesync.sh ] && DEFAULT_NTP='true' #created by psync package.
     [ -f /tmp/settertime ] && DEFAULT_NTP='true' #created by psync package.
     CHKBOXNTP='
     <hbox>
       <checkbox tooltip-text="'$(gettext "Set this computer's time and date from an Internet NTP server")'" xalign="0" space-expand="true" space-fill="true">
         <label>'$(gettext "Time from Internet")'</label>
         <variable>CHECK_NTP</variable>
         <default>'${DEFAULT_NTP}'</default>
       </checkbox>
        <button>
          '"`/usr/lib/gtkdialog/xml_button-icon info mini`"'
          <action>help ntp</action>
        </button>
     </hbox>'
    fi

    #130701...
    SPOT_XML=''
    HOMEUSER="`whoami`"
    if [ "$HOMEUSER" = "root" ];then
     SPOT_XML='
     <hbox space-expand="false" space-fill="false">
       <hbox space-expand="true" space-fill="true">
       <text space-expand="true" space-fill="true"><label>""</label></text>
       </hbox>
       <checkbox tooltip-text="'$(gettext 'Tick this if interested in running Internet applications as non-root user spot, for extra security')'" space-expand="false" space-fill="false">
         <label>'$(gettext 'Run Internet apps as spot')'</label>
         <variable>CHECK_SPOT</variable>
         <default>false</default>
       </checkbox>
         <button space-expand="false" space-fill="false">
         '"`/usr/lib/gtkdialog/xml_button-icon info mini`"'
         <action>basichtmlviewer /usr/share/doc/root.htm & </action>
       </button>
     </hbox>'
    fi

    CRDW_XML=''
    if [ -s /etc/iso3166-1-alpha2 ] \
      && which crda &>/dev/null;then #170609...
     DEFAULT_2CH='00'
     [ -f /etc/modprobe.d/crdw.conf ] && DEFAULT_2CH="$(cat /etc/modprobe.d/crdw.conf | grep '^options cfg80211' | cut -f 2 -d '=')" #created by quicksetup
     [ ! "$DEFAULT_2CH" ] && DEFAULT_2CH='00'
     DEFAULT_CRDW="$(grep "^${DEFAULT_2CH} " /etc/iso3166-1-alpha2)" #ex: AU Australia
     [ ! "$DEFAULT_CRDW" ] && DEFAULT_CRDW='00 UNSET'
     DEFAULT_CRDW_ITEM="<item>${DEFAULT_CRDW}</item>"
     if [ "$DEFAULT_2CH" == "00" ];then
      ITEMS="$(sed -e 's%^%<item>%' -e 's%$%</item>%' /etc/iso3166-1-alpha2)"
     else
      ITEMS="<item>00 UNSET</item>$(sed -e 's%^%<item>%' -e 's%$%</item>%' /etc/iso3166-1-alpha2)"
     fi
     TT_crdw="$(gettext 'To use WiFi channels 12-14 where legal or to avoid using them where illegal, choose the country where you are using WiFi -- if your WiFi device(s) cannot use those channels, you can leave it unset (00)')"
     T_crdw="$(gettext 'CRD:')"
     CRDW_XML='<hbox space-expand="false" space-fill="false">
     <text><label>'${T_crdw}'</label></text>
     <combobox tooltip-text="'${TT_crdw}'" width-request="143">
     '${DEFAULT_CRDW_ITEM}'
     '${ITEMS}'
     <variable>COMBO_CRDW</variable></combobox>
     <button>
       '"`/usr/lib/gtkdialog/xml_button-icon info mini`"'
       <action>help crdw</action>
     </button></hbox>'
    fi #170609 end
    
    NETWORK_XML='
    <frame '$(gettext 'Network')'>
      <hbox space-expand="true" space-fill="true">
        <vbox space-expand="false" space-fill="false">
          <hbox space-expand="false" space-fill="false">
            <checkbox tooltip-text="'${FWTT}'" xalign="0" space-expand="true" space-fill="true">
              <label>'$(gettext "Firewall enabled")'</label>
              <variable>CHECK_FIREWALL</variable>
              <default>'${DEFAULT_FIREWALL}'</default>
              <sensitive>'${ONLINE}'</sensitive>
            </checkbox>
            <button space-expand="false" space-fill="false">
              '"`/usr/lib/gtkdialog/xml_button-icon info mini`"'
              <action>help firewall</action>
            </button>
          </hbox>
          '${CHKBOXNTP}'
        </vbox>
        <text space-expand="true" space-fill="true"><label>""</label></text>

        <vbox space-expand="false" space-fill="false">
          '${SPOT_XML}'
        </vbox>
        <text space-expand="true" space-fill="true"><label>""</label></text>
        <vbox space-expand="false" space-fill="false">
          <hbox space-expand="false" space-fill="false">
            <text space-expand="false" space-fill="false"><label>'$(gettext 'Hostname:')'</label></text>
            <entry tooltip-text="'$(gettext 'Type your computer name to identify in the network. Alpha-numeric without spaces.')'" width-chars="15" space-expand="false" space-fill="false">
              <input>echo -n "'$HOSTNAME'"</input>
              <variable>ENTRY_HOSTNAME</variable>
            </entry>
            <button space-expand="false" space-fill="false">
              '"`/usr/lib/gtkdialog/xml_button-icon info mini`"'
              <action>help net</action>
            </button>
          </hbox>
          '${CRDW_XML}'
        </vbox>
      </hbox>
    </frame>' #170609 170610
 #fi
fi

###Country localization###
if [ "$SET_COUNTRY" ];then

 #120402
 INSTLANGPACK="`grep '^langpack_' /root/.packages/woof-installed-packages | cut -f 2 -d '|'`"
 [ ! "$INSTLANGPACK" ] && [ -f /root/.packages/user-installed-packages ] && INSTLANGPACK="`grep '^langpack_' /root/.packages/user-installed-packages | cut -f 2 -d '|'`"
 [ ! "$INSTLANGPACK" ] && INSTLANGPACK="none"

 ###Choose locale###
 LOCALEXML=""
 if [ "$SET_LOCALE" ];then
  CURRLANG="`grep '^LANG=' /etc/profile | tr -d "'" | tr -d '"' | cut -f 2 -d '='`" #111022
  [ ! "$CURRLANG" ] && CURRLANG="en_US" #precaution
  UTF8=''
  if [ "`echo -n "$CURRLANG" | grep 'utf8'`" != "" ];then #111022 get rid of old name.
   rm -rf /usr/lib/locale/$CURRLANG
   UTF8='.UTF-8'
  fi
  [ "`echo -n "$CURRLANG" | grep 'UTF\-8'`" != "" ] && UTF8='.UTF-8'
  BASELANG="`basename $CURRLANG .utf8`"
  BASELANG="`basename $BASELANG .UTF-8`"
  #does the locale need to have UTF-8 enabled?...
  UTF_FLAG="no"
  grep -q "^${BASELANG}[_. ].*ISO-8859-" /usr/share/i18n/SUPPORTED
  [ $? -ne 0 ] && UTF_FLAG="yes" #actually, alternate code below to determine this.

  if [ "$PARAM1" != "composeonly" ];then #param passed to chooselocale by 3builddistro in Woof.
   #want to default to utf8, but localedef crash problem in 64MB PC...
   if [ "$UTF8" = "" ];then
    [ ! -d /usr/lib/locale/en_US ] && localedef -f ISO-8859-1 -i en_US --no-archive en_US >/dev/null
   else
    #warning: free output varies different versions of busybox (also early version do not accept params)...
    RAMK=`free | tr -s ' ' | grep -o 'Mem:.*' | cut -f 2 -d ' '`
    if [ $RAMK -gt 100000 ];then
     #111022 no, i seem to have been lead up the garden path, the dir must remain as 'en_US.utf8'...
     [ ! -d /usr/lib/locale/en_US.utf8 ] && localedef -f UTF-8 -i en_US --no-archive en_US.utf8 >/dev/null #110409 111022
    else
     [ ! -d /usr/lib/locale/en_US ] && localedef -f ISO-8859-1 -i en_US --no-archive en_US >/dev/null
     UTF8=''
    fi
   fi
  fi

  #build language table...
 LANGUAGEDESCR='
 aa:Afar
 ab:Abkhazian
 af:Africaans
 am:Amharic
 an:Aragonese
 ar:Arabic
 az:Azeri
 be:Belarusian
 bg:Bulgarian
 bn:Bengali
 br:Breton
 bs:Bosnian
 ca:Catalan
 cs:Czech
 cy:Welsh
 da:Danish
 de:German
 dv:Divehi
 dz:Dzongkha
 el:Greek
 en:English
 eo:Esperanto
 es:Spanish
 et:Estonian
 eu:Basque
 fa:Persian
 fi:Finnish
 fo:Faeroese
 fr:French
 ga:Irish
 gd:Scots_Gaelic
 gl:Galician
 gu:Gujarati
 gv:Manx_Gaelic
 he:Hebrew
 hi:Hindi
 hr:Croatian
 hu:Hungarian
 hy:Armenian
 id:Indonesian
 is:Icelandic
 it:Italian
 iw:Hebrew
 ja:Japanese
 ka:Georgian
 kk:Kazakh
 kl:Greenlandic
 km:Khmer
 kn:Kannada
 kok:Konkani
 ko:Korean
 ku:Kurdish
 kw:Cornish
 ky:Kyrgyz
 lg:Luganda
 lo:Lao
 lt:Lithuanian
 lv:Latvian
 mg:Malagasy
 mi:Maori
 mk:Macedonian
 ml:Malayalam
 mn:Mongolian
 mr:Marathi
 ms:Malay
 mt:Maltese
 ne:Nepali
 nl:Dutch
 nb:Norgwegian
 nn:Norwegian_Nynorsk
 no:Norwegian_Bokm
 oc:Occitan
 om:Oromo
 or:Oriya
 pa:Pashto
 pa:Punjabi
 pl:Polish
 pt:Portuguese
 quz:Quechua
 ro:Romania
 rs:Serbian
 ru:Russian
 rw:Kinyarwanda
 sa:Sanskrit
 se:Sami
 sma:Sami
 smj:Sami
 smn:Sami
 sms:Sami
 sl:Slovenian
 sq:Albanian
 sr:Srpski
 sv:Swedish
 sw:Swahili
 syr:Syriac
 ta:Tamil
 te:Telugu
 th:Thai
 tl:Tagalog
 tr:Turkish
 tt:Tatar
 uk:Ukrainian
 ur:Urdu
 uz:Uzbek
 vi:Vietnamese
 wa:Walloon
 xh:Xhosa
 yi:Yiddish
 zh:Chinese
 zu:Zulu'

 REGIONDESCR='
 AA:ArabicCountries
 AE:UAE
 AL:Yugoslavia
 AR:Argentina
 AT:Austria
 AU:Australia
 BE:Belgium
 BG:Bularia
 BH:Bahrain
 BN:Brunei
 BO:Bolvia
 BR:Brazil
 BZ:Belize
 CA:Canada
 CH:Switzerland
 CL:Chile
 CN:PeoplesRepublicChina
 CO:Columbia
 CR:CostaRica
 CY:Cyprus
 CZ:CzechRepublic
 DE:Germany
 DK:Denmark
 DO:DominicanRepublic
 DO:Dominican
 DZ:Algeria
 EC:Ecuador
 EC:Ecuador
 EE:Estonia
 EG:Egypt
 ES:Spain
 FI:Finland
 FR:France
 GB:GreatBritain
 GR:Greece
 GT:Guatemalia
 HK:HongKong
 HN:Honduras
 HR:Croatia
 HU:Hungary
 ID:Indonesia
 IE:Ireland
 IL:Israel
 IN:India
 IQ:Iraq
 IS:Iceland
 IT:Italy
 JM:Jamaica
 JO:Jordan
 JP:Japan
 KR:Korea
 KW:Kuwait
 KZ:Kazakhstan
 LB:Lebanon
 LI:Liechtenstein
 LU:Luxembourg
 LY:Libya
 MA:Morocco
 MC:Monaco
 MK:Macedonia
 MO:Macau
 MY:Malaysia
 MX:Mexico
 MX:Mexico
 NI:Nicaragua
 NI:Nicaragua
 NL:Netherlands
 NO:Norway
 NZ:NewZealand
 OM:Oman
 PA:Panama
 PE:Peru
 PE:Peru
 PH:Philippines
 PL:Poland
 PR:PuertoRico
 PT:Portugal
 PY:Paraguay
 QA:Qatar
 RO:Romania
 RU:Russia
 SA:SaudiArabia
 SE:Sweden
 SG:Singapore
 SK:Slovakia
 SV:ElSalvador
 SY:Syria
 TH:Thailand
 TN:Tunisia
 TR:Turkey
 TW:Taiwan
 TT:Trinidad
 US:USA
 UY:Uruguay
 VE:Venezuela
 YE:Yemen
 YU:Yugoslavia
 ZA:SouthAfrica
 ZA:SouthAfrica'

  #need sanity check, as format of these files has changed...
  SANITYFLAG='pass'
  [ -f /usr/share/i18n/dialog_table_x ] || SANITYFLAG='fail' #111113 precaution.
  [ -s /usr/share/i18n/dialog_table_cli ] && [ `cat /usr/share/i18n/dialog_table_cli | wc -l` -le 1 ] && SANITYFLAG='fail'
  [ -s /usr/share/i18n/dialog_table_x ] && [ `cat /usr/share/i18n/dialog_table_x | wc -l` -le 1 ] && SANITYFLAG='fail'
  if [ "$PARAM1" = "composeonly" -o "$SANITYFLAG" = "fail" ];then
   #CHOICES_CLI=""; ON=""; OFF=""; CHOICES_X="" #120717 remove XPID="";
   rm -f /tmp/quicksetup_language_x;rm -f /tmp/quicksetup_language_cli
   for ONELOCALE in `ls -1 /usr/share/i18n/locales | grep -v -E 'i18n|iso|translit|POSIX'`
   do
    STATUS="off"
    [ "$ONELOCALE" = "$BASELANG" ] && STATUS="on"
    LANGUAGE="${ONELOCALE%%_*}"
    REGION=`echo -n "${ONELOCALE#*_}" | cut -f 1 -d '.' | cut -f 1 -d '@'`
    lPATTERN="^${LANGUAGE}:"
    LANGUAGE=`echo "$LANGUAGEDESCR" | tr ' ' '\n' | grep "$lPATTERN" | head -n 1 | cut -f 2 -d ':'`
    rPATTERN="^${REGION}:"
    REGION=`echo "$REGIONDESCR" | tr ' ' '\n' | grep "$rPATTERN" | head -n 1 | cut -f 2 -d ':'`
    [ "$LANGUAGE" -a "$REGION" ] && LANGUAGE="${LANGUAGE}, "
    DESCR="${LANGUAGE}${REGION}"
    if [ "$STATUS" = "on" ];then
     echo "$ONELOCALE \"${DESCR}\" on" >>/tmp/quicksetup_language_x
     FIRSTLINE_CLI="$ONELOCALE \"${DESCR}\" "
     touch /tmp/quicksetup_language_cli
     sed -i '1 i\\'"$FIRSTLINE_CLI" /tmp/quicksetup_language_cli
    else
     echo "$ONELOCALE \"${DESCR}\" off" >>/tmp/quicksetup_language_x
     echo "$ONELOCALE \"${DESCR}\" " >>/tmp/quicksetup_language_cli
    fi
   done
   cat /tmp/quicksetup_language_x >/usr/share/i18n/dialog_table_x
   [ $? = 0 ] && rm /tmp/quicksetup_language_x
   cat /tmp/quicksetup_language_cli >/usr/share/i18n/dialog_table_cli
   [ $? = 0 ] && rm /tmp/quicksetup_language_cli
   [ "$PARAM1" = "composeonly" ] && exit
  fi

  #tables already exist, but may need to reselect 'on' item...
  onPTN="s%^${BASELANG} \"(.*)\" off$%${BASELANG} \"\1\" on%"
  sed -i -e 's% on$% off%' -r -e "$onPTN" /usr/share/i18n/dialog_table_x

  DEFAULTXML=""
  DEFAULT=`grep ' on$' /usr/share/i18n/dialog_table_x | sed -e 's% on$%%' -e 's%"%%g' -e "s% %  ${TABCHAR}%"`
  [ "$DEFAULT" ] && DEFAULTXML="<item>${DEFAULT}</item>" #111107 combobox does not support default tag.
  ITEMS=`sed -e 's% on$%%' -e 's% off$%%' -e 's%"%%g' -e "s% %  ${TABCHAR}%" -e 's%^%<item>%' -e 's%$%</item>%' /usr/share/i18n/dialog_table_x`

  DEFAULT_UTF8='false'
  [ "$UTF8" ] && DEFAULT_UTF8='true'
  CHECKUTF8XML='
  <hbox tooltip-text="'$(gettext 'Tick checkbox to support UTF-8 encoding')'" space-expand="true" space-fill="true">
    <checkbox space-expand="false" space-fill="false">
      <label>'$(gettext 'UTF-8 encoding')'</label>
      <variable>CHECK_UTF8</variable>
      <default>'${DEFAULT_UTF8}'</default>
    </checkbox>
    <text space-expand="true" space-fill="true"><label>""</label></text>
    <button space-expand="false" space-fill="false">
       '"`/usr/lib/gtkdialog/xml_button-icon info mini`"'
       <action>help utf8</action>
    </button>
  </hbox>'
  LOCALEXML='
  <vbox space-expand="false" space-fill="false">
    <hbox tooltip-text="'$(gettext "Main Language")'" space-expand="true" space-fill="true">
      '"`/usr/lib/gtkdialog/xml_pixmap country_language.svg icon`"'
      <text width-request="10" space-expand="false" space-fill="false"><label>""</label></text>
      <vbox space-expand="true" space-fill="true">'
        [ "$(grep -E "countrywizard|quickcountry" <<< "$MYBASE")" ] && LOCALEXML=$LOCALEXML'<text use-markup="true" xalign="0" yalign="1" height-request="20" space-expand="true" space-fill="true"><label>"<b>'$(gettext "Main language")'</b>"</label></text>'
        LOCALEXML=$LOCALEXML'
        <hbox tooltip-text="'$(gettext "Choose main language")'" space-expand="true" space-fill="true">
          <combobox space-expand="true" space-fill="true">
            '${DEFAULTXML}'
            '${ITEMS}'
            <variable>COMBO_LOCALE</variable>
          </combobox>
          <button space-expand="false" space-fill="false">
            '"`/usr/lib/gtkdialog/xml_button-icon info mini`"'
            <action>help locale</action>
          </button>
        </hbox>
        '${CHECKUTF8XML}'
      </vbox>
    </hbox>
  </vbox>'
 fi #end SET_LOCALE

 ###Choose timezone###
 TIMEZONEXML=""
 if [ "$SET_TIMEZONE" ];then
  [ -L /etc/localtime -a ! -e /etc/localtime ] && rm -f /etc/localtime
  CZONE='/usr/share/zoneinfo/GMT0'
  DEF_TIMEZONE='GMT0'
  if [ -L /etc/localtime ] ; then
   CZONE="`readlink /etc/localtime`"
   DEF_TIMEZONE="`readlink /etc/localtime | sed -e 's%/usr/share/zoneinfo/%%'`"
  fi
  DEF_TIMEZONE=`echo -n "$DEF_TIMEZONE" | sed -e 's%Etc/%%'`
  xDEF_TIMEZONE="`echo -n "$DEF_TIMEZONE" | sed 's%GMT%GMT\\\\%'`"  #the sign needs a \ in front. ex: GMT\+8
  #120901 fix for new layout in ubuntu precise...
  ZONEINFO="`find /usr/share/zoneinfo -mindepth 2 -type f -o -type l | grep -v -E 'UTC|Greenwich|UCT|Universal|Zulu|posix|right' | sed -e 's%/usr/share/zoneinfo/%%' -e 's%Etc/%%' | tr ' ' '_' | sort | tr '\n' ' '`"
  if [ ! -f /var/local/quicksetup-timezone-table-x -o ! -f /var/local/quicksetup-timezone-table-cli ];then
   rm -f /var/local/quicksetup-timezone-table-x
   rm -f /var/local/quicksetup-timezone-table-cli
   ZONECHOICES_CLI=""
   for ONEZONE in $ZONEINFO
   do
    ONEDESCR="."
    [ "$ONEZONE" = "GMT" ] && continue
    [ "$ONEZONE" = "GMT-0" ] && continue
    case $ONEZONE in
     GMT+0)     ONEDESCR='(London, Dublin, Edinburgh, Lisbon, Reykjavik, Casablanca)';;
     GMT-1)     ONEDESCR='(Azores, Cape Verdes)';;
     GMT+1)     ONEDESCR='(Paris, Berlin, Amsterdam, Brussels, Madrid, Stockholm Oslo)';;
     GMT-2)     ONEDESCR='(mid-Atlantic)';;
     GMT+2)     ONEDESCR='(Athens, Helsinki, Istanbul, Jerusalem, Harare)';;
     GMT-3)     ONEDESCR='(Brasilia, Buenos Aires, Georgetown)';;
     GMT+3)     ONEDESCR='(Kuwait, Nairobi, Riyadh, Moscow)';;
     GMT-4)     ONEDESCR='(Caracas, La Paz, Canada)';;
     GMT+4)     ONEDESCR='(Abu Dhabi, Muscat, Tblisi, Volgograd, Kabul)';;
     GMT-5)     ONEDESCR='(Bogota, Lima, New York)';;
     GMT+5)     ONEDESCR='(Islamabad, Karachi)';;
     GMT+5:30)  ONEDESCR='(India)';;
     GMT-6)     ONEDESCR='(Mexico City, Saskatchewan)';;
     GMT+6)     ONEDESCR='(Almaty, Dhaka)';;
     GMT+6:30)  ONEDESCR='(Cocos Islands)';;
     GMT-7)     ONEDESCR='(Alberta, Montana, Arizona)';;
     GMT+7)     ONEDESCR='(Bangkok, Jakarta)';;
     GMT-8)     ONEDESCR='(Los Angeles)';;
     GMT+8)     ONEDESCR='(Perth, Singapore, Hongkong)';;
     GMT-9)     ONEDESCR='(Alaska)';;
     GMT+9)     ONEDESCR='(Tokyo)';;
     GMT+9:30)  ONEDESCR='(Darwin, Adelaide)';;
     GMT-10)    ONEDESCR='(Alaska, Hawaii)';;
     GMT+10)    ONEDESCR='(Guam)';;
     GMT+10:30) ONEDESCR='(Lord Howe Island)';;
     GMT-11)    ONEDESCR='(Samoa)';;
     GMT+11)    ONEDESCR='(Magadan, Soloman Is.)';;
     GMT-12)    ONEDESCR='(Eniwetok)';;
     GMT+12)    ONEDESCR='(Wellington, Fiji, Marshall Islands)';;
     GMT+13)    ONEDESCR='(Rawaki Islands)';;
     GMT+14)    ONEDESCR='(Line Islands)';;
    esac
     echo -n "${ONEZONE} \"${ONEDESCR}\" " >> /var/local/quicksetup-timezone-table-cli #111113
    if [ "$DEF_TIMEZONE" = "${ONEZONE}" ];then
     echo "${ONEZONE} \"${ONEDESCR}\" on" >> /var/local/quicksetup-timezone-table-x
    else
     echo "${ONEZONE} \"${ONEDESCR}\" off" >> /var/local/quicksetup-timezone-table-x
    fi
   done
  fi
  ZONECHOICES_CLI="`cat /var/local/quicksetup-timezone-table-cli`" #111113

  #table already exist, but may need to reselect 'on' item...
  onPTN="s%^${xDEF_TIMEZONE} \"(.*)\" off$%${DEF_TIMEZONE} \"\1\" on%"
  sed -i -e 's% on$% off%' -r -e "$onPTN" /var/local/quicksetup-timezone-table-x

  DEFAULTXML=""
  DEFAULT=`grep ' on$' /var/local/quicksetup-timezone-table-x | sed -e 's% on$%%' -e 's%"%%g' -e "s% %${TABCHAR}%"`
  [ "$DEFAULT" ] && DEFAULTXML="<item>${DEFAULT}</item>" #111107 combobox does not support default tag.
  ITEMS=`sed -e 's% on$%%' -e 's% off$%%' -e 's%"%%g' -e "s% %${TABCHAR}%" -e 's%^%<item>%' -e 's%$%</item>%' /var/local/quicksetup-timezone-table-x`

  DEFAULT_UTC="false"
  [ "$HWCLOCKTIME" = "utc" ] && DEFAULT_UTC="true" #see /etc/clock
  CHECKUTCXML='
  <hbox tooltip-text="'$(gettext 'Tick checkbox if hardware clock is set to UTC, untick if hardware clock set to local time')'" space-expand="true" space-fill="true">
    <checkbox space-expand="false" space-fill="false">
      <label>'$(gettext 'Hardware clock set to UTC')'</label>
      <variable>CHECK_UTC</variable>
      <default>'${DEFAULT_UTC}'</default>
    </checkbox>
    <text space-expand="true" space-fill="true"><label>""</label></text>
    <button space-expand="false" space-fill="false">
       '"`/usr/lib/gtkdialog/xml_button-icon info mini`"'
       <action>help utc</action>
    </button>
  </hbox>'

  TIMEZONEXML='
  <vbox space-expand="false" space-fill="false">
    <hbox tooltip-text="'$(gettext "Time Zone")'" space-expand="true" space-fill="true">
      '"`/usr/lib/gtkdialog/xml_pixmap country_timezone.svg icon`"'
      <text width-request="10" space-expand="false" space-fill="false"><label>""</label></text>
      <vbox space-expand="true" space-fill="true">'
         [ "$(grep -E "countrywizard|quickcountry" <<< "$MYBASE")" ] && TIMEZONEXML=$TIMEZONEXML'<hseparator></hseparator><text use-markup="true" xalign="0" yalign="1" height-request="30" space-expand="true" space-fill="true"><label>"<b>'$(gettext "Time zone")'</b>"</label></text>'
        TIMEZONEXML=$TIMEZONEXML'
        <hbox tooltip-text="'$(gettext "Choose time zone")'" space-expand="true" space-fill="true">
          <combobox space-expand="true" space-fill="true">
            '${DEFAULTXML}'
            '${ITEMS}'
            <variable>COMBO_TIMEZONE</variable>
          </combobox>
          <button space-expand="false" space-fill="false">
            '"`/usr/lib/gtkdialog/xml_button-icon info mini`"'
            <action>help timezone</action>
          </button>
        </hbox>
        '${CHECKUTCXML}'
      </vbox>
    </hbox>
  </vbox>'
 fi #end SET_TIMEZONE

 ###keyboard layout###
 KEYBOARDXML=""
 if [ "$SET_KEYBOARD" ];then
  # Check if the keyboard needs any kernel modules
  [ "$(which initmodules)" -a ! -f /mnt/home${PSUBDIR}/${DISTRO_FILE_PREFIX}initmodules.txt ] && initmodules -q & # [ ... -a "$PUPMODE" = "5" ] could do instead
  xkbconfigmanager layouttable #creates /var/tmp/xkblayout-table
  DEFAULTXML=""
  DEFAULT=`grep ' on$' /var/tmp/xkblayout-table | sed -e 's% on$%%' -e 's%"%%g' -e "s% %    ${TABCHAR}%"`
  [ "$DEFAULT" ] && DEFAULTXML="<item>${DEFAULT}</item>" #111107 combobox does not support default tag.
  ITEMS=`sed -e 's% on$%%' -e 's% off$%%' -e 's%"%%g' -e "s% %    ${TABCHAR}%" -e 's%^%<item>%' -e 's%$%</item>%' /var/tmp/xkblayout-table`

  DEFAULT_NUMLOCK="false"
  CHECKNUMLOCKXML=""
  if which numlockx >/dev/null;then
   [ -x $HOME/Startup/numlockx ] && [ "`grep '^numlockx on' $HOME/Startup/numlockx`" != "" ] && DEFAULT_NUMLOCK="true"
   CHECKNUMLOCKXML='
   <hbox tooltip-text="'$(gettext 'Tick checkbox to turn on keyboard numlock')'" space-expand="true" space-fill="true">
     <checkbox space-expand="false" space-fill="false">
       <label>'$(gettext 'Keyboard numlock')'</label>
       <variable>CHECK_NUMLOCK</variable>
       <default>'${DEFAULT_NUMLOCK}'</default>
     </checkbox>
     <text space-expand="true" space-fill="true"><label>""</label></text>
     <button space-expand="false" space-fill="false">
       '"`/usr/lib/gtkdialog/xml_button-icon info mini`"'
       <action>help numlock</action>
     </button>
   </hbox>'
  fi

  KEYBOARDXML='
  <vbox space-expand="false" space-fill="false">
    <hbox tooltip-text="'$(gettext "Keyboard Layout")'" space-expand="true" space-fill="true">
      '"`/usr/lib/gtkdialog/xml_pixmap country_keyboard.svg icon`"'
      <text width-request="10" space-expand="false" space-fill="false"><label>""</label></text>
      <vbox space-expand="true" space-fill="true">'
         [ "$(grep -E "countrywizard|quickcountry" <<< "$MYBASE")" ] && KEYBOARDXML=$KEYBOARDXML'<hseparator></hseparator><text use-markup="true" xalign="0" yalign="1" height-request="30" space-expand="true" space-fill="true"><label>"<b>'$(gettext "Keyboard Layout")'</b>"</label></text>'
        KEYBOARDXML=$KEYBOARDXML'<hbox tooltip-text="'$(gettext "Choose keyboard layout")'" space-expand="true" space-fill="true">
          <combobox space-expand="true" space-fill="true">
            '${DEFAULTXML}'
            '${ITEMS}'
            <variable>COMBO_KEYBOARD</variable>
          </combobox>
          <button space-expand="false" space-fill="false">
            '"`/usr/lib/gtkdialog/xml_button-icon info mini`"'
            <action>help keyboard</action>
          </button>
        </hbox>
        '${CHECKNUMLOCKXML}'
      </vbox>
    </hbox>
  </vbox>'
 fi #end SET_KEYBOARD

 COUNTRYXML='
 <vbox>
   <frame '${COUNTRYFRAMETITLE}'>
     '${LOCALEXML}'
     '${TIMEZONEXML}'
     '${KEYBOARDXML}'
   </frame>
 </vbox>'
fi #end SET_COUNTRY

###setup x###
if [ "$SET_XWIZARD" ];then
  #put up a button to launch xorgwizard...
  XDRIVERSUCCESS=$(report-video driver)
  if [ "$XDRIVERSUCCESS" ];then #precaution.
    TT_xorg1=$(gettext 'Run the Xorg Video Wizard')
    TT_xorg2=$(gettext 'Xorg Video Wizard')
    B_xwiz=$(gettext 'Run Video Wizard')
    XMSGX=$(gettext "The <b>${XDRIVERSUCCESS}</b> video driver is currently being used. Ok, if you need to adjust screen resolution or displacement, run the Video Wizard.")
    XMSGRES=$(gettext "Current resolution:<b> $(report-video res) </b> ($(report-video depth) bit)")
    XWIZARDXML='
     <hbox space-expand="true" space-fill="true">
       '"`/usr/lib/gtkdialog/xml_pixmap graphics.svg icon`"'
       <text space-expand="true" space-fill="true"><label>""</label></text>
     </hbox>
     <hbox><text use-markup="true"><label>"'${XMSGX}'"</label></text></hbox>
     <hbox space-expand="true"><text use-markup="true"><label>"'${XMSGRES}'"</label></text></hbox>
     <hbox space-expand="true" tooltip-text="'${TT_xorg2}'">
       <checkbox tooltip-text="'${TT_xorg1}'">
         <variable>CHECK_XORGWIZARD</variable>
         <label>'${B_xwiz}'</label>
       </checkbox>
     </hbox>'
  fi
fi #end SET_XWIZARD

if [ "$SET_XRES" -a ! "$SET_XWIZARD" ];then
  echo > /var/tmp/xrandrlist
  while read line ; do 
		#      $F1			$F2		 $F3      $F4
		#   800x600        75.0     72.0*    60.0 
		read -r F1 F2 F3 F4 F5 F6 <<< "$line"
		if [[ $F1 == *[0-9]x[0-9]* ]] ; then
			if [[ $line == *\** ]] ; then
				DEF_XYRES=$F1 #current resolution
				for ONEREFRESHRATE in $F2 $F3 $F4 $F5 $F6
				do
					if [[ $ONEREFRESHRATE == *\** ]] ; then #eg 60.0*
						[ -z $DEF_VFREQ ] && DEF_VFREQ=${ONEREFRESHRATE%\*}
					fi
					echo "<item>$F1 $ONEREFRESHRATE</item>" >> /var/tmp/xrandrlist
				done
			else
				for ONEREFRESHRATE in $F2 $F3 $F4 $F5 $F6
				do
					echo "<item>$F1 $ONEREFRESHRATE</item>" >> /var/tmp/xrandrlist
				done
			fi
		fi
  done <<< "$(xrandr -q)"

  ITEMS="<item>$DEF_XYRES ${DEF_VFREQ}*</item>
$(cat /var/tmp/xrandrlist | grep -v "${DEF_XYRES}.*${DEF_VFREQ}\*")"
  XYRESXML='
  <vbox space-expand="false" space-fill="false">
    '${XRANDRWARNXML}'
    <hbox tooltip-text="'$(gettext 'Xrandr Screen Resolution')'">
      <combobox tooltip-text="'$(gettext 'Set screen resolution with xrandr')'">
        '${DEFAULTXML}'
        '${ITEMS}'
        <variable>COMBO_XYRES</variable>
       </combobox>
       <button>
         '"`/usr/lib/gtkdialog/xml_button-icon info mini`"'
         <action>help resolution</action>
       </button>
     </hbox>
   </vbox>'
fi #end SET_XRES

if [ "$SET_XRES" ] ; then
 XXML='
 <vbox>
   <frame '${XFRAMETITLE}'>
     '${XWIZARDXML}'
     '${XYRESXML}'
   </frame>
 </vbox>'
fi #end SET_XRES

#120714 alternate audio/video frame for arm board... create $XXML...
if [ "$SET_RP_AUDIO" -o "$SET_RP_VIDEO" ];then
 if [ "$SET_RP_AUDIO" ];then
  RP_DEF_AUDIO='0'; RP_AUDIO_0_DEF='false'; RP_AUDIO_1_DEF='false'; RP_AUDIO_2_DEF='false'
  if [ -f /etc/init.d/11alsa_raspi ];then
   RP_DEF_AUDIO="`grep 'amixer cset numid' /etc/init.d/11alsa_raspi | rev | cut -f 1 -d ' ' | rev`" #0=auto, 1=analog, 2=hdmi.
  else #precaution. script should be provided by 'z_raspi_fixes_hack' pet.
   echo '#!/bin/sh
case $1 in
 start)
  amixer cset numid=3 0
 ;;
esac' > /etc/init.d/11alsa_raspi
   chmod 755 /etc/init.d/11alsa_raspi
  fi
  case $RP_DEF_AUDIO in
   1) RP_AUDIO_1_DEF='true' ;;
   2) RP_AUDIO_2_DEF='true' ;;
   *) RP_AUDIO_0_DEF='true' ;;
  esac
  RP_AUDIOXML="<frame $(gettext 'Raspberry Pi Audio Settings')>
   <radiobutton active=\"${RP_AUDIO_0_DEF}\"><label>$(gettext 'Automatic output routing')</label><variable>RP_AUDIO_0_RAD</variable></radiobutton>
   <radiobutton active=\"${RP_AUDIO_1_DEF}\"><label>$(gettext 'Output to round analog socket')</label><variable>RP_AUDIO_1_RAD</variable></radiobutton>
   <radiobutton active=\"${RP_AUDIO_2_DEF}\"><label>$(gettext 'Output to HDMI TV/monitor')</label><variable>RP_AUDIO_2_RAD</variable></radiobutton>
  </frame>"
 fi
 if [ "$SET_RP_VIDEO" ];then
  RP_VIDEOXML="<frame Raspberry Pi Video Settings>
   <text><label>No fancy GUI here yet! Please edit file 'config.txt' in partition #1 then reboot.</label></text>
  </frame>"
 fi
 XXML="<vbox>
  ${RP_AUDIOXML}
  ${RP_VIDEOXML}
 </vbox>"
fi



####main window####
###################
[ $XPID -ne 0 ] && kill $XPID 2> /dev/null
BACKTITLEXML=""
[ "$BACKTITLE" ] && BACKTITLEXML="`/usr/lib/gtkdialog/xml_info fixed "$ICON.svg" 60 "$(gettext "${BACKTITLE}")"`"
[ "$MYBASE" = "quicksetup" ] && MOUSEXML='
<button space-expand="false" space-fill="false">
  '"`/usr/lib/gtkdialog/xml_button-icon mouse.svg`"'
  <action>mousecheck nowait</action>
</button>
<text xalign="0" use-markup="true" space-expand="true" space-fill="true"><label>"<span color='"'red'"'><b>'$(gettext 'Dead mouse?')'</b></span> '$(gettext '<b>TAB</b> key to select this button then press <b>ENTER</b> key.')'"</label></text>
  '

WINWIDTH=""
WINWIDTHPARAM=""
B_cancel=$(gettext "Cancel")
export QUICKSETUP_DIALOG='
<window title="'${WINTITLE}'" window_position="1" icon-name="'${WINICON}'" '${WINWIDTHPARAM}'>
<vbox space-expand="true" space-fill="true">
  '${BACKTITLEXML}'
  <hbox space-expand="true" space-fill="true">
    '${COUNTRYXML}'
    '${XXML}'
  </hbox>
  '${NETWORK_XML}'
  <hbox space-expand="false" space-fill="false"> 
    '${MOUSEXML}'
    <text space-expand="true" space-fill="true"><label>""</label></text>
    <button space-expand="false" space-fill="false">
      <label>'$(gettext "Ok")'</label>
      '"`/usr/lib/gtkdialog/xml_button-icon ok`"'
      <action>exit:OK</action>
    </button>
    '"`/usr/lib/gtkdialog/xml_scalegrip`"'
  </hbox>
</vbox>
</window>'

###display main window###
wPID=0
if [ $DISPLAY ];then
 . /usr/lib/gtkdialog/xml_info gtk #build bg_pixmap for gtk-theme
 RETVALS="`gtkdialog -p QUICKSETUP_DIALOG`"
 eval "$RETVALS"
 [ "$EXIT" != "OK" -a "$EXIT" != "NVIDIA" ] && exit

 #get rid of this, as causes xorgwizard to run at next boot (see $HOME/.profile)...
 [ -f $HOME/.xorgwizard-reenter ] && rm -f $HOME/.xorgwizard-reenter

 if [ ! "$SET_XWIZARD" ];then
   /usr/lib/gtkdialog/box_splash -placement top -close never -fontsize large -text "$(gettext 'Processing, please wait...')" & #120524
   wPID=$!
 fi
else
 #replace the old single-purpose text-mode scripts...
 case $MYBASE in
  chooselocale)
   CHOICES="`cat /usr/share/i18n/dialog_table_cli | tr '\n' ' '`"
   if [ "$PARAM2" = "quiet" ];then #120215 rc.country calls 'chooselocale cli quiet'
    COMBO_LOCALE=${BASELANG} #LANG already chosen. ex: de_DE (.UTF-8 part is specified by UTF8)
   else
    echo "#!/bin/sh
dialog --aspect 10 --title \"Country setup\" --menu \"The locale setting provides money, date and font localization for your country. The current choice is ${BASELANG}. Make a choice to suit your country...\" 0 0 0 ${CHOICES} 2>/tmp/chooselocale-choice
exit \$?" > /tmp/dialog-chooselocale
    chmod 777 /tmp/dialog-chooselocale
    /tmp/dialog-chooselocale
    [ $? -ne 0 ] && exit
    COMBO_LOCALE="`cat /tmp/chooselocale-choice | head -n 1`"
   fi
   CHECK_UTF8="$DEFAULT_UTF8" #dialog box does not have a UTF-8 checkbox.
  ;;
  timezone-set)
   ZONEDLG="dialog --aspect 10 --title \"Puppy timezone selector\" --default-item $DEF_TIMEZONE --menu \"Please choose your timezone. If a city/region/country in your timezone is not listed, choose a GMT<number>\" 0 0 0 ${ZONECHOICES_CLI}"
   eval $ZONEDLG 2>/tmp/zoneretval
   [ $? -ne 0 ] && exit
   COMBO_TIMEZONE="`cat /tmp/zoneretval`"
   CHECK_UTC="$DEFAULT_UTC" #dialog box does not have a UTC checkbox.
  ;;
  *)
   exit
  ;;
 esac
fi

####process choices####
FLAG_CHANGED=""

if [ "$SET_KEYBOARD" ];then
 #two variables COMBO_KEYBOARD and CHECK_NUMLOCK
 XKB_LAYOUT="`echo -n "$COMBO_KEYBOARD" | cut -f 1 -d ' ' | cut -f 1 -d "$TABCHAR"`"
 FONTMAP=""; CODEPAGE=""
 FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'Keyboard Layout'):yes|" #111020 no need to restart X.
 sed -i "s%.*Option.*XkbLayout.*%	Option      \"XkbLayout\" \"${XKB_LAYOUT}\"%" /etc/X11/xorg.conf
 xkbconfigmanager apply
 #-
 #120224 fontmap will be handled in locale code below.
 if [ "$DEFAULT_NUMLOCK" != "$CHECK_NUMLOCK" ];then
  FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'Keyboard numlock'):yes|"
  STATUS_NUMLOCK=off
  [ "$CHECK_NUMLOCK" = "true" ] && STATUS_NUMLOCK=on
  echo -e "#!/bin/sh\nnumlockx ${STATUS_NUMLOCK}" > $HOME/Startup/numlockx
  chmod 755 $HOME/Startup/numlockx
  numlockx ${STATUS_NUMLOCK} #do it now.
 fi
fi #end SET_KEYBOARD

if [ "$SET_LOCALE" ];then
 #two variables, COMBO_LOCALE and CHECK_UTF8
 LANGCHOICE="`echo -n "$COMBO_LOCALE" | cut -f 1 -d ' ' | cut -f 1 -d '@'`" #nl_BE@euro, need to chop.
 UTF8=""
 [ "$CHECK_UTF8" = "true" ] && UTF8='.UTF-8'

 #120215 rc.country calls 'chooselocale cli quiet'
 [ "$PARAM2" = "quiet" ] && CURRLANG=en_US #so as to force below code block to run...

 if [ "$LANGCHOICE" != "" -a "${LANGCHOICE}${UTF8}" != "$CURRLANG" ];then
  FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'Main Language'):restart|"
  # creates locale files in /usr/lib/locale...
  OLDLANGLINE="LANG=$CURRLANG"
  NEWLANGLINE="LANG=${LANGCHOICE}"
  xUTF8="$UTF8"
  if [ "$UTF8" != "" ];then #111022
   NEWLANGLINE="LANG=${LANGCHOICE}"'.UTF-8'
   xUTF8='.utf8'
  fi
  if [ "`locale -a | grep "${LANGCHOICE}${xUTF8}$"`" = "" ];then #120228 L18L bugfix.
   if [ "$UTF8" = "" ];then
    lcPATTERN='^'"${LANGCHOICE}"' '
    CHARMAP="`grep "$lcPATTERN" /usr/share/i18n/SUPPORTED | head -n 1 | cut -f 2 -d ' '`"
    if [ "$CHARMAP" != "" ];then #make sure have it...
     cPATTERN="$CHARMAP"'\.gz'
     [ "`ls -1 /usr/share/i18n/charmaps | grep '.gz$'`" = "" ] && cPATTERN="$CHARMAP"'$'
     [ "`ls -1 /usr/share/i18n/charmaps | grep "$cPATTERN"`" = "" ] && CHARMAP=""
    fi
    if [ "$CHARMAP" != "" ];then
     localedef -f $CHARMAP -i $LANGCHOICE --no-archive ${LANGCHOICE} > /dev/null
     NEWLANGLINE="LANG=${LANGCHOICE}"
     UTF8="" #120209
    else
     #no match, i think forced to use utf8... 111022 change name back to .utf8...
     localedef -f UTF-8 -i $LANGCHOICE --no-archive ${LANGCHOICE}.utf8 > /dev/null
     NEWLANGLINE="LANG=${LANGCHOICE}.UTF-8"
     UTF8='.UTF-8'
    fi
   else
    localedef -f UTF-8 -i $LANGCHOICE --no-archive ${LANGCHOICE}.utf8 > /dev/null #111022
    NEWLANGLINE="LANG=${LANGCHOICE}.UTF-8"
   fi
  fi
  NEWLANG="`echo -n "$NEWLANGLINE" | cut -f 2 -d '='`" #ex: de_DE.UTF-8

  if [ "$OLDLANGLINE" != "$NEWLANGLINE" ];then
   langPATTERN="s%^LANG=.*%${NEWLANGLINE}%" #111022
   sed -i -e "$langPATTERN" /etc/profile
   #120328 code moved up, to be compatible for chooselocale call from rc.country...
   #120224 load console font... (code based on that in 'init')
   #120301 don't load console font here. seems to get dropped on exit from X. (instead, do it in xwin. now have /sbin/load_consolefont)
   case $NEWLANG in
    en*)
     #er, no, really want to unload all console fonts.
     echo -n "" > /etc/fontmap #well, next boot, no font will be loaded.
    ;;
    ar*|iw*) #L18L no Greek
     echo -n 'LatArCyrHeb-16.psfu' > /etc/fontmap
    ;;
    *) #L18L All European languages; new default ?!
     echo -n 'LatGrkCyr-8x16.psfu' > /etc/fontmap
    ;;
   esac
  fi

  if [ "$PARAM2" = "quiet" ];then #120215 refer to /etc/rc.d/rc.country.
   #scripts fixdesk and fixmenus translate files to new language (as specified in /usr/share/sss/menu_strings and desk_strings).
   #so need to call them here...
   #note, these are also called in /etc/rc.d/rc.update, and further down.
   LANG=${NEWLANG} fixdesk
   LANG=${NEWLANG} fixmenus
   exit
  fi
  [ "$MYBASE" = "chooselocale" ] && [ "$PARAM1" = "cli" ] && exit #refer rc.country.

  if [ "$OLDLANGLINE" != "$NEWLANGLINE" ];then
   #120213 need language-pack...
   LANG1=${LANGCHOICE%_*}  #"`echo -n $LANGCHOICE | cut -f 1 -d '_'`"  #ex: de
   LANG12=${LANGCHOICE%.*} #"`echo -n $LANGCHOICE | cut -f 1 -d '.'`" #ex: de_DE
   l1PTN="|langpack_${LANG1}|"
   l12PTN="|langpack_${LANG12}|"
   if [ "$LANG1" != "en" ];then
    LANGFLAG='no'
    [ "`grep "$l12PTN" /root/.packages/woof-installed-packages`" != "" ] && LANGFLAG='yes'
    [ "`grep "$l12PTN" /root/.packages/user-installed-packages`" != "" ] && LANGFLAG='yes'
    [ "`grep "$l1PTN" /root/.packages/woof-installed-packages`" != "" ] && LANGFLAG='yes'
    [ "`grep "$l1PTN" /root/.packages/user-installed-packages`" != "" ] && LANGFLAG='yes'
    if [ "$LANGFLAG" = "no" ];then

     #check if a langpack available...
     case $NEWLANG in #120313 hardcode translations... 120315
      fr*) #French, esmourguit
       AVAILMSG1="Il y a un paquet \Zb${AVAILPACK}\ZB dans le répertoire \Zbnoarch\ZB, catégorie \ZbSetup\ZB. Après être connecté à Internet, cliquer sur l'icône du bureau \Zbinstall\ZB pour lancer le Gestionnaire des Paquets, puis choisir le répertoire et la catégorie.
Remarque: Avant de télécharger le paquet, vous devrez établir une connexion Internet et utiliser le Gestionnaire des Paquets en anglais. Si vous ne comprenez pas l'anglais, l'alternative consiste à lancer avec un autre système d'exploitation, d'aller sur le site http://distro.ibiblio.org/quirky/pet_packages-noarch et télécharger le Langpack. Redémarrez Puppy, cliquez sur l'icône des partitions du bureau pour monter la partition (où est téléchargé le Langpack) et cliquez sur le fichier pour l'installer."
       AVAILMSG2="Les Langpacks officiels sont disponibles dans \Zbnoarch\ZB, mais il n'y en a pas pour votre langue. Peut-être y en a-t'il un en développement dans le forum (attention, certaines anciennes versions de Puppy possèdent des Langpacks incompatibles). Peut-être voulez-vous aider et/ou créer un Langpack - cliquez sur le menu -> Aide -> HOWTO internationalisation (vous devrez connaitre bien l'anglais)."
       AVAILTITLE="Langpack nécessaire"
       AVAILMSG3="La locale sera changée en ${LANGCHOICE}, mais vous devez installer un Langpack pour avoir Puppy dans votre langue. Vous avez besoin du paquet \Zblangpack_${LANG12}\ZB ou \Zblangpack_${LANG1}\ZB. Ce n'est pas encore automatisé, vous devrez donc télécharger et installer le paquet vous même. Vous pourrez le faire à n'importe quel moment plus tard. Les Langpacks bénéficiant d'un soutien officiel sont disponibles dans le Gestionnaire des Paquets (cliquez sur l'icône du bureau \Zbinstall\ZB ), et dans le répertoire \Zbnoarch\ZB."
      ;;
      de*) #German, L18L
       AVAILMSG1="Es gibt ein passendes Sprachpaket \Zb${AVAILPACK}\ZB in der Kategorie \ZbSetup\ZB des PET-Repositoriums \Zbnoarch\ZB. Bei vorhandener Internetverbindung ein Klick auf das Symbol \Zbinstall\ZB auf dem Desktop und dann ein Klick auf Puppy Package Manager startet diesen. Im Paketmanager dann Kategorie Setup und Repo: puppy-noarch wählen.
Hinweis: Vor dem Herunterladen des Sprachpakets muß eine Internetverbindung hergestellt sein und der Puppy-Paket-Manager auf Englisch benutzt werden. Falls man glaubt, dies nicht auf Englisch hinzukriegen, kann man alternativ mit einem anderen Betriebssystem das langpack, Sprachpaket, herunterladen von http://distro.ibiblio.org/quirky/pet_packages-noarch. Dann Puppy hochfahren, ein Klick auf das Partitions-Symbol auf dem Desktop hängt die Partition ein, auf die das Sprachpaket heruntergeladen wurde und ein Klick auf das Sprachpaket-PET installiert es dann."
       AVAILMSG2="Offizielle langpacks, Sprachpakete, sind im Repositorium \Zbnoarch\ZB vefügbar, jedoch keines für deutsch. Vielleicht ist eines in Entwicklung im Puppy Forum (aber Achtung: einige ältere Puppy-Versionen haben inkompatible langpacks, Sprachpakete.). Oder \"Do It Yourself\":  klick Menü -> Hilfe -> HOWTO Internationalization (you will of course need a good knowledge of English; und deshalb bleibt dieser Satz unübersetzt)."
       AVAILTITLE="Sprachpaket erforderlich"
       AVAILMSG3="Die locale wird geändert in ${LANGCHOICE}, aber es muß ein Sprachpaket installiert werden, um Puppy auf deutsch laufen zu lassen. Ein PET-Paket namens \Zblangpack_${LANG12}\ZB oder \Zblangpack_${LANG1}\ZB wird gebraucht. Wir habe dies noch nicht automatisiert, sodaß man das Paket noch selbst herunterladen und installieren muß, das ist auch irgendwann in der Zukunft noch möglich. Offiziell unterstützte langpacks, Sprachpakete, sind im Puppy Package Manager (Klick auf das Symbol \Zbinstall\ZB auf dem Desktop), im Repo: \Zbpuppy-noarch\ZB zu finden."
      ;;
      es*) #Spanish, vicmz
       AVAILMSG1="Hay un paquete \Zb${AVAILPACK}\ZB apropiado en el respositorio de PETs \Zbnoarch\ZB, en la categoría \ZbConfiguración\ZB. Después de tener una conexión a Internet, pulse el ícono \Zbinstalar\ZB del escritorio para abrir el Administrador de Paquetes, luego elija el repositorio y la categoría.
Nota: Antes de descargar el paquete de idioma, tendrá que hacer una conexión a Internet y usar el Administrador de Paquetes (Puppy Package Manager) en inglés. Si piensa que no sabe leer inglés lo suficiente, una alternativa es usar otro sistema operativo, ir a http://distro.ibiblio.org/quirky/pet_packages-noarch y descargar el paquete de idioma. Entonces, inicie Puppy, haga clic en el ícono de partición (donde descargó el paquete de idioma), y haga clic en el PET de paquete de idioma para instalarlo."
       AVAILMSG2="Hay paquetes de idioma oficiales disponibles en el repositorio \Zbnoarch\ZB, sin embargo no hay uno para su idioma. Tal vez haya uno en desarrollo en el Foro de Puppy (cuidado, algunas versiones más antiguas de Puppy tienen paquetes incompatibles). Ó, tal vez usted pueda ofrecerse como voluntario para ayudar y crear un paquete de idioma (haga clic en Menu -> Help -> HOWTO Internationalization, por supuesto usted necesitará un buen conocimiento de inglés)."
       AVAILTITLE="Se necesita un paquete de idioma"
       AVAILMSG3="El idioma se cambiará a ${LANGCHOICE}, pero usted necesita instalar un paquete de idioma para traducir Puppy a su lengua. Usted necesita un paquete PET llamado \Zblangpack_${LANG12}\ZB o \Zblangpack_${LANG1}\ZB. No hemos automatizado esto aún, así que tendrá que descargar e instalar el paquete. Puede hacer esto en cualquier momento en el futuro. Hay paquetes de idioma con soporte oficial disponibles usando el Administrador de Paquetes (Puppy Package Manager) (haga clic en el ícono \Zbinstalar\ZB del escritorio), en el repositorio \Zbnoarch\ZB. "
      ;;
      it*) #Italian, vicmz
       AVAILMSG1="C'è un pacchetto \Zb${AVAILPACK}\ZB idoneo nel repository di PET \Zbnoarch\ZB, nella categoria \ZbImpostazioni\ZB. Una volta ottenuto una connessione a Internet, fare clic sull'icona \Zbinstallare\ZB sul desktop per eseguire l'Amministratore di Pacchetti, quindi scegli il repository e la categoria.
Nota: Prima di scaricare il pacchetto di lingua, si dovrà effettuare una connessione a Internet e utilizzare l'Amministratore di Pacchetti (Puppy Package Manager) in lingua inglese. Se pensi che non puoi leggere l'inglese a sufficienza, un'alternativa è quella di eseguire un altro sistema operativo, andare a http://distro.ibiblio.org/quirky/pet_packages-noarch e scaricare il pacchetto di lingua. Poi, avvia Puppy, clicca sull'icona di partizione sul desktop per montare la partizione (dove ai scaricato il pacchetto di lingua), quindi clicca sul PET del pacchetto di lingua per installarlo."
       AVAILMSG2="Pacchetti di lingua ufficiali sono disponibili nel repository \Zbnoarch\ZB, ma non ce n'è uno per tua lingua. Forse ce n'è uno in fase di sviluppo nel Forum Puppy (attenzione, alcune vecchie versioni di Puppy hanno pacchetti di lingua incompatibili). O, forse potrebbe volontari per aiutare e creare un pacchetto di lingua -- fare clic sul Menu -> Help -> HOWTO Internationalization (ovviamente hai bisogno di una buona conoscenza della lingua inglese)."
       AVAILTITLE="È necessario un pacchetto di lingua"
       AVAILMSG3="La lingua sarà cambiata in ${LANGCHOICE}, però hai bisogno d'installare un pacchetto di lingua per tradurre Puppy nella tua lingua. Hai bisogno di un pacchetto PET chiamato \Zblangpack_${LANG12}\ZB o \Zblangpack_${LANG1}\ZB. Non abbiamo ancora automatizzato questa azione, quindi dovrete scaricare e installare il pacchetto. Puoi fare ne in qualsiasi momento in futuro. Pacchetti di lingua ufficialmente supportati sono disponibili eseguendo l'Amministratori di Pacchetti (Puppy Package Manager) (clicca l'icona \Zbinstallare\ZB sul desktop), nel repository \Zbnoarch\ZB."
      ;;
      nl*) #Netherlands (Dutch), FlyingDutchman 120701 fix...
       AVAILMSG1="Er is een geschikt \Zb${AVAILPACK}\ZB pakket in de \Zbnoarch\ZB PET repository, in de \ZbSetup\ZB categorie. Klik op het \Zbinstall\ZB pictogram op het bureaublad om de Puppy Package Manager te starten en kies vervolgens de repository en categorie.
Opmerking: Voor het downloaden van het taalpakket is een werkende internetverbinding nodig. Tevens moet de Puppy Package Manager in het Engels worden gebruikt. Als u Engels hiervoor onvoldoende beheerst is het ook mogelijk om vanuit een ander besturingssysteem naar http://distro.ibiblio.org/quirky/pet_packages-noarch te gaan en het taalpakket (langpack_nl) te downloaden. Start daarna Puppy op, klik op het pictogram van de partitie waarop het taalpakket is opgeslagen en klik vervolgens op de taalpakket PET om het te installeren."
       AVAILMSG2="Er zijn officiële taalpakketten beschikbaar in de \Zbnoarch\ZB repository maar helaas is er geen taalpakket gevonden voor uw taal. Wellicht wordt er aan een vertaling gewerkt in het Puppy Forum (pas op, sommige oudere Puppy versies gebruiken taalpakketten die niet uitwisselbaar zijn). Of misschien wilt u helpen bij het creëren van een taalpakket -- Klik Menu -> Help -> HOWTO Internationalization (U hebt hiervoor uiteraard een goede kennis van het Engels voor nodig)."
       AVAILTITLE="Taalpakket nodig"
       AVAILMSG3="De standaard taal wordt gewijzigd naar ${LANGCHOICE}, maar u moet een taalpakket installeren om Puppy in uw taal te vertalen. U hebt daarvoor een PET pakket nodig met de naam \Zblangpack_${LANG12}\ZB of \Zblangpack_${LANG1}\ZB. We hebben dit nog niet geautomatiseerd dus u zult dit zelf moeten downloaden en installeren. U kunt dit op elk gewenst moment doen. Officeel ondersteunde taalpakketten zijn beschikbaar door het de Puppy Package Manager te starten (klik op het \Zbinstall\ZB pictogram op het bureaublad), in de \Zbnoarch\ZB repository."
      ;;
      pl*) #120331 Polish, robwoj44 (Robert)
       AVAILMSG1="Jest odpowiedni pakiet \Zb${AVAILPACK}\ZB w repozytorium \Zbnoarch\ZB PET, w kategorii \ZbSetup\ZB. Po uzyskaniu połączenia z Internetem, kliknij ikonę \Zbinstall\ZB na pulpicie by uruchomić Puppy Package Manager, potem wybierz repozytorium i kategorię.
Uwaga: Przed pobraniem pakietu językowego, trzeba mieć połączenie z Internetem i użyć Puppy Manager Pakietów po angielsku. Jeśli myślisz że nie zrozumiesz po angielsku dostatecznie, alternatywą jest uruchomienie innego systemu operacyjnego, wejście na http://distro.ibiblio.org/quirky/pet_packages-noarch i pobranie pakietu językowego. Następnie, rozruch Puppy, kliknięcie ikony partycji na pulpicie by zamontować partycję (tą gdzie ściągnąłeś pakiet językowy), potem kliknięcie na pakiecie językowym PET by go zainstalować."
       AVAILMSG2="Oficjalne pakiety językowe są dostępne w repozytorium \Zbnoarch\ZB, jednak gdy nie ma dla twojego języka. Możliwe że jest jakiś w przygotowaniu na Forum Puppy (uważaj, niektóre starsze wersje Puppy mają niekompatybilne pakiety językowe). Albo, możesz dobrowolnie pomóc i stworzyć pakiet językowy -- kliknij Menu -> Help -> HOWTO Internationalization (oczywiście będziesz potrzebował dobrej znajomości angielskiego)."
       AVAILTITLE="Pakiet językowy potrzebny"
       AVAILMSG3="Ustawienia regionalne będą zmienione na ${LANGCHOICE}, ale musisz zainstalować pakiet językowy by przetłumaczyć Puppy na swój język. Potrzebujesz pakietu PET nazwanego \Zblangpack_${LANG12}\ZB lub \Zblangpack_${LANG1}\ZB. Jeszcze nie zautomatyzowaliśmy tego, zatem musisz pobrać i zainstalować pakiet. Możesz to zrobić w każdym czasie w przyszłości. Oficjalnie obsługiwane pakiety językowe są dostępne przez uruchomienie Puppy Package Manager (kliknij ikonę \Zbinstall\ZB na pulpicie), w repozytorium \Zbnoarch\ZB."
      ;;
      pt*) #Portuguese, vicmz
       AVAILMSG1="Há um pacote \Zb${AVAILPACK}\ZB apropriado no respositório de PETs \Zbnoarch\ZB, na categoria \ZbConfiguração\ZB. Após ter uma conexão a Internet, clique o ícone \Zbinstalar\ZB da Área de Trabalho para abrir o Administrador de Pacotes, então escolha o repositório e a categoria.
Nota: Antes de transferir o pacote de língua, você terá que fazer uma conexão a Internet e usar o Administrador de Pacotes (Puppy Package Manager) em inglês. Se pensar que não sabe ler inglês o bastante, uma alternativa é usar outro sistema operativo, ir para http://distro.ibiblio.org/quirky/pet_packages-noarch e descarregar o pacote de língua. Então, inicie Puppy, clique no ícone de partição (onde descarregou o pacote de língua), e clique no PET do pacote de língua para instalá-lo."
       AVAILMSG2="Há pacotes de língua oficiais disponíveis no repositório \Zbnoarch\ZB, porém não há um para sua língua. Talvez há um em desenvolvimento no Fórum de Puppy (atenção, algumas versões mais antigas de Puppy têm pacotes incompatíveis). Ou, talvez você possa se oferecer como voluntário para ajudar e criar um pacote de língua (clique no Menu -> Help -> HOWTO Internationalization, certamente você precisará um bom conhecimento de inglês)."
       AVAILTITLE="Precisa-se de um pacote de língua"
       AVAILMSG3="A língua será mudada para ${LANGCHOICE}, mas você precisa instalar um pacote de língua para traduzir Puppy em sua língua. Você precisa um pacote PET chamado de \Zblangpack_${LANG12}\ZB ou \Zblangpack_${LANG1}\ZB. Nós não temos automatizado isto ainda, asim que você terá que descarregar e instalar o pacote. Você pode fazer isto em qualquer momento no futuro. Há pacotes com suporte oficial disponíveis usando o Administrador de Pacotes (Puppy Package Manager) (clique no ícone \Zbinstalar\ZB na Área de Trabalho), no repositório  \Zbnoarch\ZB. "
      ;;
      ru*) #Russian, rodin.s
       AVAILMSG1="Есть подходящий пакет \\Zb${AVAILPACK}\\ZB в \\Zbnoarch\\ZB PET-репозитарии, в категории \\ZbSetup\\ZB. После того, как у вас появится подключение к Интернет нажмите значок \\Zbinstall\\ZB на рабочем столе для запуска Менеджера пакетов Puppy, затем выберите репозитарий и категорию.
Примечание: Перед загрузкой пакета локализации вы должны будете настроить подключение к Интернет и использовать Менеджер пакетов Puppy на английском. Если вы думаете, что не знаете английский достаточно хорошо, альтернатива - это запуск другой операционной системы, зайдете на http://distro.ibiblio.org/quirky/pet_packages-noarch и загрузите пакет локализации. После этого загрузите Puppy, нажмите на значок раздела на рабочем столе для монтирования раздела (на который вы загрузили пакет локализации), затем кликните на сам PET-пакет лангпака для его установки."
       AVAILMSG2="Официальные пакеты локализации доступны в \\Zbnoarch\\ZB-репозитарии, однако для вашего языка нет пакета. Возможно пакет для вашего языка в разработке на форуме Puppy (будте осторожны, пакеты для старых версий Puppy не подходят). Или, возможно, вы захотите помочь и создать пакет -- Кликните Меню -> Справка -> HOWTO Internationalization (конечно же вам будет нужно хорошее знание английского языка)."
       AVAILTITLE="Нужен пакет локализации"
       AVAILMSG3="Локаль будет изменена на ${LANGCHOICE}, но вам нужно установить языковой пакет для перевода Puppy на ваш язык. Вам нужен PET-пакет с названием \\Zblangpack_${LANG12}\\ZB или \\Zblangpack_${LANG1}\\ZB. Этот процесс ещё не автоматизирован, так, что вам нужно загрузить и установить пакет. Вы можете сделать это в любое время в будущем. Официально поддерживаемые пакеты локализации доступны в Менеджере пакетов Puppy (кликните значок \\Zbinstall\\ZB на рабочем столе), в репозитарии \\Zbnoarch\\ZB."
      ;;
      *)
       AVAILMSG1="There is a suitable \Zb${AVAILPACK}\ZB package in the \Zbnoarch\ZB PET repository, in the \ZbSetup\ZB category. After you have an Internet connection, click the \Zbinstall\ZB icon on the desktop to run the Puppy Package Manager, then choose the repository and category.
Note: Before downloading the langpack, you will have to make an Internet connection and use the Puppy Package Manager in English. If you think that you cannot read English sufficiently, an alternative is to run another operating system, go to http://distro.ibiblio.org/quirky/pet_packages-noarch and download the langpack. Then, boot Puppy, click the partition icon on the desktop to mount the partition (where you downloaded the langpack to), then click on the langpack PET to install it."
       AVAILMSG2="Official langpacks are available in the \Zbnoarch\ZB repository, however there is not one for your language. Perhaps there is one under development in the Puppy Forum (be careful, some older versions of Puppy have incompatible langpacks). Or, perhaps you might volunteer to help out and create a langpack -- click the Menu -> Help -> HOWTO Internationalization (you will of course need a good knowledge of English)."
       AVAILTITLE="Language pack needed"
       AVAILMSG3="The locale will be changed to ${LANGCHOICE}, but you need to install a language pack to translate Puppy to your language. You need a PET package named \Zblangpack_${LANG12}\ZB or \Zblangpack_${LANG1}\ZB. We have not yet automated this, so you will have to download and install the package. You may do this any time in the future. Officially supported langpacks are available by running the Puppy Package Manager (click the \Zbinstall\ZB icon on the desktop), in the \Zbnoarch\ZB repository."
      ;;
     esac
     AVAILPACK=''
     AVAILMSG="$AVAILMSG2"
     [ "`grep "$l12PTN" /root/.packages/Packages-puppy-noarch-official`" != "" ] && AVAILPACK="langpack_${LANG12}"
     [ "`grep "$l1PTN" /root/.packages/Packages-puppy-noarch-official`" != "" ] && AVAILPACK="langpack_${LANG1}"
     [ "$AVAILPACK" ] && AVAILMSG="$AVAILMSG1"
     if [ "$DISPLAY" ];then
      [ $wPID -ne 0 ] && kill $wPID #120524
      wPID=0
      LANG=${NEWLANG} pupdialog --background '#8080FF' --colors --backtitle "${AVAILTITLE}" --msgbox "${AVAILMSG3}\n\n${AVAILMSG}" 0 0
     else
      dialog --msgbox "`eval_gettext \"Note, you will need to install langpack_\\\${LANG12} or langpack_\\\${LANG1} PET package to more fully translate Puppy to your language. Run the Puppy Package Manager after connection to the Internet, to download and install this package.\"`" 0 0 >/dev/console
     fi
    fi
   fi

   #120215 offer to translate initrd... 120216 moved to separate script (so universal installer can also do it)...
   GIVEITAGO='yes'
   NEWLANG1=${NEWLANG%_*} #ex: en
   #120401 change logic to call lang2initrd...
   PLANG1=""
   [ "PLANG" ] && PLANG1="${PLANG%_*}" #defined in PUPSTATE by initrd.
   [ "$NEWLANG1" = "en" ] && GIVEITAGO='no'
   if [ -f /var/local/lang2initrd.log ];then #read log from /usr/sbin/lang2initrd
    [ "`grep "^DECLINED ${DISTRO_IDSTRING}" /var/local/lang2initrd.log`" != "" ] && GIVEITAGO='no'
    [ "`grep "^SUCCESS ${DISTRO_IDSTRING}" /var/local/lang2initrd.log`" != "" ] && GIVEITAGO='no'
   fi
   if [ "$PLANG1" ];then #120401
    [ "$PLANG" != "$NEWLANG" ] && GIVEITAGO='yes' #catch case of user only changing UTF-8 checkbox.
    if [ "$PLANG1" != "$NEWLANG1" ];then
     GIVEITAGO='yes'
     [ "$NEWLANG1" != "en" ] && echo -n "" > /var/local/lang2initrd.log #so wmpoweroff/wmreboot can run lang2initrd after langpack installed.
    fi
   fi
   [ "$GIVEITAGO" = "yes" ] && /usr/sbin/lang2initrd $NEWLANG #note, script has more tests, then asks if want translate initrd.

   #120209 scripts fixdesk and fixmenus translate files to new language (as specified in /usr/share/sss/menu_strings and desk_strings).
   #so need to call them here...
   #note, these are also called in /etc/rc.d/rc.update ...
   LANG=${LANGCHOICE}${UTF8} fixdesk
   LANG=${LANGCHOICE}${UTF8} fixmenus
   #...no need to refresh screen, as changing locale requires restart of X.

  fi
 fi
fi #end SET_LOCALE

if [ "$SET_TIMEZONE" ];then
 #two variables, COMBO_TIMEZONE and CHECK_UTC
 ZONERETVAL="`echo -n "$COMBO_TIMEZONE" | cut -f 1 -d ' ' | cut -f 1 -d "$TABCHAR"`"
 NEW_HWCLOCKTIME="localtime"
 [ "$CHECK_UTC" = "true" ] && NEW_HWCLOCKTIME="utc"
 [ ! -e /etc/localtime ] && DEF_TIMEZONE="" #111027 precaution.
 if [ "$DEF_TIMEZONE" != "$ZONERETVAL" -o "$HWCLOCKTIME" != "$NEW_HWCLOCKTIME" ];then
  FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'Time Zone'):yes|"
  [ "`echo "$ZONERETVAL" | grep 'GMT'`" != "" ] && ZONERETVAL="Etc/$ZONERETVAL"
  #111103 these are also in Etc dir...
  [ "$ZONERETVAL" = "Greenwich" ] && ZONERETVAL="Etc/$ZONERETVAL"
  [ "$ZONERETVAL" = "UCT" ] && ZONERETVAL="Etc/$ZONERETVAL"
  [ "$ZONERETVAL" = "Universal" ] && ZONERETVAL="Etc/$ZONERETVAL"
  [ "$ZONERETVAL" = "UTC" ] && ZONERETVAL="Etc/$ZONERETVAL"
  [ "$ZONERETVAL" = "Zulu" ] && ZONERETVAL="Etc/$ZONERETVAL"
  ln -snf /usr/share/zoneinfo/$ZONERETVAL /etc/localtime
  which xset &>/dev/null && xset s noblank s noexpose -dpms  #shinobar 30jan11: avoid the screen go to blank

  #need to set Linux system time/date, from hardware clock...
  set_hwclock_type -q --hctosys ${NEW_HWCLOCKTIME}
 fi
fi #end SET_TIMEZONE

if [ "$SET_XRES" ];then
 #one variable COMBO_XYRES
 read -r NEW_XYRES NEW_VFREQ <<< "$COMBO_XYRES"
 NEW_VFREQ=${NEW_VFREQ%\*} #remove trailing "*"
 if [ "$DEF_XYRES $DEF_VFREQ" != "$NEW_XYRES $NEW_VFREQ" ];then
  FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'Xrandr Screen Resolution'):yes|"
  T_yesno="`gettext 'Change resolution to:'`"
  M_yesno1="`gettext 'Click the OK button to change the resolution.'`"
  M_yesno2="`gettext 'If the new resolution does not work, wait 60 seconds, or hit the CTRL-ALT-BACKSPACE key combination to kill X.'`"
  M_yesno3="$(gettext 'Note, the drive icons may be in wrong place after resolution change, but will be correct after X is restarted.')" #120226
  [ $wPID -ne 0 ] && kill $wPID #120524
  wPID=0
  pupdialog --background yellow --backtitle "${T_yesno} ${NEW_XYRES}@${NEW_VFREQ}" --yes-label "$B_ok" --no-label "$B_cancel" --yesno "${M_yesno1}\n${M_yesno2}\n${M_yesno3}" 0 0 #130202
  if [ $? -eq 0 ];then
   echo "ICONWIPE" > /var/local/pup_event_icon_change_flag #120226 .xinitrc -> clean_desk_icons will read this, and redraw drive icons.
   sync
   xrandr -s $NEW_XYRES -r $NEW_VFREQ 2>/tmp/xrandr_error #this changes the screen resolution. #130202 add freq.
   if [ "$?" -ne "0" ];then
     # try without frequency
     xrandr -s $NEW_XYRES 2>/dev/null
     bFLG=1 #flag so correct entry entered to /etc/xrandrindex
     if [ "$?" -ne "0" ];then
       BMSG=`cat /tmp/xrandr_error`
       /usr/lib/gtkdialog/box_splash -bg red -close box -timeout 5 -text "$BMSG" & #put out the old error, maybe it will work anyway, does here
       rm /tmp/xrandr_error
       unset bFLG
       exit
     fi
   fi
   sleep 1
   XRANDR="`xrandr -q`"
   TESTLINE="$(echo "$XRANDR" | tr -s " " | grep "^ [0-9]" | grep '\*' | head -n 1)" #130202 'head -n 1' workaround for dual monitors (see also .xinitrc).
   
   TESTX="`echo -n "$TESTLINE" | cut -f 2 -d " " | cut -f 1 -d 'x'`"
   TESTY="`echo -n "$TESTLINE" | cut -f 2 -d " " | cut -f 2 -d 'x'`"
   TESTVR="`echo -n "$TESTLINE" |tr ' ' '\n' | grep "\*" | cut -f 1 -d '*'`" 

   M_y0=$(gettext 'Can you see this?')
   M_y1=$(gettext "Click <b>Permanent</b> button to keep this resolution permanently.
Click <b>Session</b> button to keep this resolution for current session only.
Click <b>Cancel</b> button to revert to default resolution.")
   M_y2=$(gettext "<b>Warning</b>
It is NOT recommended to choose <b>Permanent</b> here, as the default resolution is not really changed, instead it switches resolutions after X has started, which causes a delay and flicker at startup and may have other undesirable side-effects. Instead, run the Video Wizard to choose a permanent resolution.")
   B_permanent=$(gettext 'Permanent')
   B_session=$(gettext 'Session')
   STEP=6   # timeout is x10sec
   fontsize="x-large" # small, medium, large, x-large  130203 fix insertion of fontsize...
   export XY_DIALOG="<window title=\"$WINTITLE\" icon-name=\"gtk-preferences\"><vbox>
    <text use-markup=\"true\"><label>\"<span size='${fontsize}'>${M_y0}</span>\"</label></text>
    <text use-markup=\"true\"><label>\"${M_y1}\"</label></text>
    <text use-markup=\"true\"><label>\"${M_y2}\"</label></text>
    <progressbar><input>for i in \$(seq 0 10 100); do echo \$i; sleep $STEP; done;echo 100</input>
      <label>$(gettext 'Or, it will be canceled in 60 seconds.')</label>
      <action type=\"exit\">TIMEOUT</action></progressbar>
    <hbox>
     <button><label>${B_permanent}</label><action>EXIT:permanent</action></button>
     <button><label>${B_session}</label><action>EXIT:session</action></button>
     <button><label>${B_cancel}</label><action>EXIT:cancel</action></button>
    </hbox>
    </vbox></window>"
   eval $(gtkdialog -p XY_DIALOG --center)
   case $EXIT in
    permanent)
     case $bFLG in
      1)echo -n "${TESTX}x${TESTY}" > /etc/xrandrindex ;;
      *)echo -n "${TESTX}x${TESTY}@${TESTVR}" > /etc/xrandrindex ;; #so will be set in .xinitrc at next X start. #130202 added freq.
     esac
    ;;
    session)
     rm -f /etc/xrandrindex
    ;;
    *)
     rm -f /etc/xrandrindex
     xrandr -s $DEF_XYRES -r $DEF_VFREQ #restore to what it was before. #130202 added freq.
    ;;
   esac

  fi
 fi
fi #end SET_XRES

if [ "$SET_XWIZARD" ];then
 if [ "$CHECK_XORGWIZARD" = "true" ];then
  #FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'Xorg Video Wizard'):restart|" #"Xorg Video Wizard"
  xorgwizard first
  echo "ICONWIPE" > /var/local/pup_event_icon_change_flag #120226 .xinitrc -> clean_desk_icons will read this, and redraw drive icons. ...actually, redundant, as xorgwizard does this.
 fi
fi #end SET_XWIZARD

if [ "$SET_NETWORK" ];then #120227

 #120625 set new hostname...
 OLD_HOSTNAME="$HOSTNAME"
 if [ "$OLD_HOSTNAME" != "$ENTRY_HOSTNAME" ];then
  /usr/sbin/hostname-set $ENTRY_HOSTNAME
  HOSTNAMEFLAG=$?
  [ "$HOSTNAMEFLAG" = "0" ] && FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'Hostname'):restart|"
  [ "$HOSTNAMEFLAG" = "2" ] && FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'Hostname'):yes|" #130511 see hostname-set.
 fi

 #120625...
 if [ "$CHECK_FIREWALL" != "$DEFAULT_FIREWALL" ];then
  if [ "$CHECK_FIREWALL" = "false" ];then
   /etc/rc.d/rc.firewall stop 2>/dev/null
   /etc/init.d/rc.firewall stop 2>/dev/null
   chmod 664 /etc/rc.d/rc.firewall 2>/dev/null #so that /etc/rc.d/rc.local won't start it.
   chmod 664 /etc/init.d/rc.firewall 2>/dev/null #ugh
   FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'Firewall disabled'):yes|"
  else
   FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'Firewall enabled'):yes|"
   if [ -f /etc/rc.d/rc.firewall ];then
    chmod 755 /etc/rc.d/rc.firewall #so that /etc/rc.d/rc.local will start firewall at bootup.
    /etc/rc.d/rc.firewall start
   elif [ -f /etc/init.d/rc.firewall ];then
    chmod 755 /etc/init.d/rc.firewall #ugh
    /etc/init.d/rc.firewall start
   else
    [ $(which firewallinstallshell) ] && rxvt -bg LightYellow -title "Firewall setup" -e firewallinstallshell
    [ $(which firewall_ng) ] && firewall_ng
   fi
  fi
 fi

 #120625...
 if [ "$CHECK_NTP" != "$DEFAULT_NTP" ];then
  if [ "$CHECK_NTP" = "false" ];then
   chmod 664 $HOME/Startup/timesync.sh #so it won't run next bootup.
   FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'NTP set-time disabled'):yes|"
  else
   [ -f $HOME/Startup/timesync.sh ] && chmod 755 $HOME/Startup/timesync.sh
   if [ -x $HOME/Startup/timesync.sh ];then
    $HOME/Startup/timesync.sh &
    FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'NTP set-time enabled'):yes|"
   else
    /usr/local/psync/psync
    if [ -x $HOME/Startup/timesync.sh ];then
     FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'NTP set-time enabled'):yes|"
    else
     #/tmp/settertime created by /usr/local/psync/psyncfunc
     [ -f /tmp/settertime ] && FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'NTP set-time (this session only)'):yes|"
    fi
   fi
  fi
 fi

 if [ "$DEFAULT_CRDW" != "$COMBO_CRDW" ];then #170609...
  NEW_CRDW="$(echo -n "$COMBO_CRDW" | cut -f 1 -d ' ')" #ex: AU
  echo "options cfg80211 ieee80211_regdom=${NEW_CRDW}" > /etc/modprobe.d/crdw.conf #set at the next bootup.
  #...at bootup, after module cfg80211 loads, can confirm setting by running 'iw reg get'
  #BK: had taken this out, but seems still need it on my laptop. may need to expand this script, with a loop, keep plugging away until the setting gets forced. but for now, just do it once...
  echo "#!/bin/ash
  iw reg set ${NEW_CRDW}" > /etc/init.d/z-wifi-puppy
  chmod 755 /etc/init.d/z-wifi-puppy
  iw reg set ${NEW_CRDW} #set now.
  FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'CRD changed to') ${NEW_CRDW}:yes|"
 fi #170609 end

 #130701...
 if [ $DISPLAY ];then
  if [ "$CHECK_SPOT" = "true" ];then
   [ $wPID -ne 0 ] && kill $wPID
   wPID=0
   loginmanager
  fi
 fi

fi

#120714 raspberry pi support...
if [ "$SET_RP_AUDIO" -o "$SET_RP_VIDEO" ];then
 if [ "$SET_RP_AUDIO" ];then
  RP_AUDIO_OUT='0'
  [ "$RP_AUDIO_0_RAD" = "true" ] && RP_AUDIO_OUT='0' #auto
  [ "$RP_AUDIO_1_RAD" = "true" ] && RP_AUDIO_OUT='1' #analog
  [ "$RP_AUDIO_2_RAD" = "true" ] && RP_AUDIO_OUT='2' #hdmi
  if [ "$RP_DEF_AUDIO" != "$RP_AUDIO_OUT" ];then
   rpPTN="s%amixer cset numid.*%amixer cset numid=3 ${RP_AUDIO_OUT}%"
   sed -i -e "$rpPTN" /etc/init.d/11alsa_raspi
   amixer cset numid=3 ${RP_AUDIO_OUT} #do it now.
   case $RP_AUDIO_OUT in
    0) FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'Automatic audio output'):yes|" ;;
    1) FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'Analog audio output'):yes|" ;;
    2) FLAG_CHANGED="${FLAG_CHANGED}$(gettext 'HDMI audio output'):yes|" ;;
   esac
  fi
 fi
 if [ "$SET_RP_VIDEO" ];then
  echo
 fi
fi

[ ! $DISPLAY ] && exit

if [ "`echo -n "$FLAG_CHANGED" | grep "restart"`" != "" ];then

 F_restart="`gettext 'restart'`"
 rPTN="s%:restart% <b><big>${F_restart}</big></b>%"
 CHANGEDMARKUP="`echo "$FLAG_CHANGED" | tr '|' '\n' | sed -e "$rPTN" | cut -f 1 -d ':'`"
 H_t1="`gettext 'Quick Setup: finished'`"
 B_restart="`gettext 'Restart X'`"
 B_exit="`gettext 'Exit'`"
 M_fc0="`gettext 'These are the changed items:'`"
 M_fc1="`gettext 'Those marked with <b>restart</b> require a restart of X (the graphical desktop) to take effect. Recommend, if it is ok to continue without restarting X for now, choose that option (<b>Exit</b> button).'`"
 M_fc2="`gettext 'Make sure no other applications are running, and click the <b>Restart X</b> button, which will exit from the graphical desktop and restart it.'`"
 M_fc3="`gettext 'Or, if the <b>Exit</b> button is clicked, the desktop will be retained, and changes marked with <b>restart</b> will not take effect. However, they will take effect the next time that X is started.'`"
 export FC_DIALOG="<window title=\"${H_t1}\" window_position=\"1\" icon-name=\"${WINICON}\">
<vbox>
  <text use-markup=\"true\"><label>\"${M_fc0}\"</label></text>
  <text use-markup=\"true\"><label>\"<i>${CHANGEDMARKUP}</i>\"</label></text>
  <text use-markup=\"true\"><label>\"${M_fc1}\"</label></text>
  <text use-markup=\"true\"><label>\"${M_fc2}\"</label></text>
  <text use-markup=\"true\"><label>\"${M_fc3}\"</label></text>
  <hbox>
    <button><label>${B_restart}</label><input file stock=\"gtk-redo\"></input><action>EXIT:OK</action></button>
    <button><label>${B_exit}</label><input file stock=\"gtk-quit\"></input><action>EXIT:cancel</action></button>
  </hbox>
</vbox>
</window>"
 [ $wPID -ne 0 ] && kill $wPID #120524
 wPID=0
 RETVALS="`gtkdialog -p FC_DIALOG`"
 eval "$RETVALS"
 if [ "$EXIT" = "OK" ];then
  rm -rf /tmp/.X0-lock
  sync
  exec restartwm
 fi
fi

[ $wPID -ne 0 ] && kill $wPID #120524
wPID=0
###END###
